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

时间:2017-08-16 18:32:33

标签: c# asp.net gridview ado.net sqldatasource

我有GridView链接到SQL表。表具有未知或可变数量的列。列数和列名都是可变的。是否可以在UpdateCommand中设置动态sqlDataSource,以便我可以更新每一列?如是;如何?

我试过的代码:

<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>

1 个答案:

答案 0 :(得分:0)

您的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
}

注意:动态更新列并不是一个好主意,您会遇到更多麻烦而不是好处。但是对于简单的场景,上面的代码可以工作。