确定在数据网格上选中了哪个复选框并更新DB

本文关键字:复选框 DB 更新 数据 数据网 网格 | 更新日期: 2023-09-27 18:07:59

我有一个数据网格与TemplateField和复选框在这个领域。我将根据数据库中的1或0将这些复选框标记为选中或未选中。

<asp:TemplateField HeaderText="Normal User Logging">
        <ItemTemplate>
            <asp:CheckBox runat="server" ID="normalLogging" Checked='<%# Eval("normal_toggle") == 1 %>'
            AutoPostBack="true" />
        </ItemTemplate>
        </asp:TemplateField>

我将有多行在这个数据网格。我想知道我将如何确定哪个复选框被选中,每当一个被选中。例如,我如何知道一个人单击了第三行复选框?

确定在数据网格上选中了哪个复选框并更新DB

使用DataGridViewCheckBoxColumn控件类型创建列,并使用Click事件和CellContentClick,参见下面的示例

    private void Form1_Load(object sender, EventArgs e)
    {
        DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
        col.Name = "ColumnName";
        col.HeaderText = "HeaderTest";
        col.TrueValue = "True";
        col.FalseValue = "False";
        this.dataGridView1.Columns.Add(col);
        this.dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);
        this.dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
    }
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName")
        {
            DataGridViewCheckBoxCell cell = this.dataGridView1.CurrentCell as DataGridViewCheckBoxCell;
            if (cell.Value == cell.TrueValue) 
               //your code here            
        }
    }
    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex >= 0 && this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName")
        {
            DataGridViewCheckBoxCell cell = this.dataGridView1.CurrentCell as DataGridViewCheckBoxCell;
            if (cell.Value == cell.TrueValue) 
             {
                //your code here
             }
        }
    }

根据你所说的,它不是Checkboxes将执行PostBack,而是一些其他按钮,所以你可以一次检查你的整个选择。在这种情况下,复选框不应该是AutoPostBack="true"

也就是说,你的Button的代码应该是这样的:
foreach (GridViewRow row in gv.Rows)
{
    CheckBox cb = row.FindControl("cb") as CheckBox;
    if (cb != null)
    {
        if(cb.Checked)
        {
            //Do your thing here
        }
    }
}

OP (Justin)发帖说他想为每次CheckBox点击更新DB。在这种情况下,解决方案是处理CheckBox的OnCheckedChanged事件:

Aspx代码:

<asp:TemplateField HeaderText="Normal User Logging">
    <ItemTemplate>
        <asp:CheckBox runat="server" ID="normalLogging" 
                      Checked='<%# Eval("normal_toggle") == 1 %>'
                      AutoPostBack="true" 
                      OnCheckedChanged="cb_CheckedChanged" 
                      yourID='<%#Eval("yourIdField") %>'/>
    </ItemTemplate>
</asp:TemplateField>

c#代码后面:

protected void cb_CheckedChanged(object sender, EventArgs e)
{
    Checkbox cb = sender as CheckBox;
    string yourID = cb.Attributes["yourID"];
    //Do your thing
}