是否可以使用可变列数更新 GridView?

Is it possible to update GridView with variable number of columns?

我有一个 GridView 链接到 SQL table。 Table 列数未知或可变。列数和列名都是可变的。是否可以在 sqlDataSource 中设置动态 UpdateCommand 以便我可以更新每一列?如是;怎么样?

我试过的代码:

<asp:GridView ID="GridView1" AutoGenerateColumns="True" ShowHeaderWhenEmpty ="True" DataSourceID="UpdateSqlDataSource"
    CssClass = "table" runat="server" AllowSorting="True" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
    CellPadding="3" DataKeyNames="UpdateID" ShowFooter="True"
    AutoGenerateDeleteButton="true" AutoGenerateSelectButton ="true" AutoGenerateEditButton="true">
    <AlternatingRowStyle BackColor="#F7F7F7" />
    <Columns>
    </Columns>
    <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
    <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
    <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
    <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
    <SortedAscendingCellStyle BackColor="#F4F4FD" />
    <SortedAscendingHeaderStyle BackColor="#5A4C9D" />
    <SortedDescendingCellStyle BackColor="#D8D8F0" />
    <SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
<asp:SqlDataSource ID ="UpdateSqlDataSource" runat ="server" ConnectionString="<%$ ConnectionStrings:MachineUpdateDataBaseConnectionString %>"
    DeleteCommand="DELETE FROM [MachineUpdate] WHERE [UpdateID] = @UpdateID"
    SelectCommand="SELECT * FROM [MachineUpdate]" UpdateCommand="UPDATE SET [MachineUpdate] = @MachineUpdate WHERE [UpdateID] = @UpdateID[*] = @* WHERE [UpdateID] = @UpdateID">
    <DeleteParameters>
            <asp:Parameter Name="UpdateID" Type="Int32" />
    </DeleteParameters>
</asp:SqlDataSource>

您的 SqlDataSource 的 UpdateCommand 始终是静态的,要生成动态更新,您应该通过处理 GridView 的 RowUpdating 事件的 C# 代码来完成。

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string sqlCommand = "UPDATE YourTable SET ";
    foreach (DictionaryEntry item in e.NewValues)
    {
        // You will need to take care to not update PK, FK, etc
        // You will need to handle DB restrictions
        // You will need to handle DataTypes (eg: Not set a boolean in a Date column)
        sqlCommand = sqlCommand + item.Key + " = " + item.Value + ",";
    }

    sqlCommand = sqlCommand.TrimEnd(','); // removes the last comma

    foreach (DictionaryEntry de in e.Keys)
    {
        //Assuming that you will have just only one key
        // You can get the Key in the GridView.DataKeyNames property as well
        sqlCommand = sqlCommand + " WHERE " + de.Key.ToString() + " = " + de.Value.ToString();
    }


    GridView grd = (GridView)sender;
    SqlDataSource ds = (SqlDataSource)grd.DataSourceObject;
    ds.UpdateCommand = sqlCommand; // Modify the UpdateCommand of you SqlDataSource
}

注意: 动态更新列不是一个好主意,您会比受益更头疼。但是对于简单的场景,上面的代码是可行的。