我有一个数据网格,每一行都有一个复选框。每行中的每个字段也可以更新
用户可以更新多行并选中任何复选框。
单击“提交”按钮后,所有数据都应更新。我需要复选框来更新数据库中的 bool 值(或者 SQL Server 的 bool 类型)。
- 如何实现复选框才能更新数据库中的表?
- 点击提交按钮后,如何获取所有要更新的数据?
最佳答案
如果您使用的是 GridView,则可以在您之前获得的示例的基础上执行此操作。 **这是半伪代码,请注意**
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
allowpaging="true"
datakeynames="CustomerID"
runat="server">
<columns>
<asp:templatefield>
<itemtemplate> <%-- This is itemtemplate so they are visible by default --%>
<asp:CheckBox ID="cbVerify" runat="server"></asp:CheckBox>
<asp:HiddenField ID="hidID" runat="server" Value='<%# Bind("CustomerID") %>'></asp:HiddenField>
</itemtemplate>
</asp:templatefield>
<asp:boundfield datafield="CustomerID" readonly="true" headertext="Customer ID"/>
<asp:boundfield datafield="CompanyName" readonly="true" headertext="Customer Name"/>
<asp:boundfield datafield="Address" headertext="Address"/>
<asp:boundfield datafield="City" headertext="City"/>
<asp:boundfield datafield="PostalCode" headertext="ZIP Code"/>
</columns>
</asp:gridview>
<asp:Button ID="btSubmit" runat="server" OnClick="btSubmit_Click"></asp:Button>
处理此问题的代码
public void btSubmit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in CustomersGridView.Rows)
{
CheckBox cbVerify = (CheckBox)row.FindControl("cbVerify");
HiddenField hidID = (HiddenField)row.FindControl("hidID");
// Do your validation of the data here
..
if (cbVerify != null)
{
// Add fields and update
sqlRecord.UpdateParameters["ID"].DefaultValue = hidID.Value;
sqlRecord.UpdateParameters["Valid"].DefaultValue = cbVerify.Checked.ToString();
sqlRecord.Update();
}
}
这应该会让您朝着特定的方向寻找。
关于c# - 使用复选框更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7655124/