确定在数据网格上检查哪个复选框并更新数据库

时间:2011-09-07 19:53:34

标签: c# asp.net data-binding datagrid

我在这个字段中有一个带有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>

我将在此数据网格中有多行。我想知道每当检查一个复选框时我将如何确定。比如,我怎么知道一个人点击了第三行复选框?

2 个答案:

答案 0 :(得分:1)

根据您所说的,不是将执行PostBack的Checkbox,而是其他一些按钮,因此您可以立即检查您的整个选择。在这种情况下,复选框不应为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点击更新数据库。在这种情况下,解决方案是处理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
}

答案 1 :(得分:1)

使用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
             }
        }
    }

此致