Determining a which checkbox is checked on a datagrid and updating DB
I have a datagrid with a TemplateField and checkbox in this field. I will marking these check boxes as either checked or not depending on a 1 or 0 in the database.
<asp:TemplateField HeaderText="Normal User Logging">
<ItemTemplate>
<asp:Che开发者_开发技巧ckBox runat="server" ID="normalLogging" Checked='<%# Eval("normal_toggle") == 1 %>'
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
I will have multiple rows in this datagrid. I am wondering how I will determine which checkbox is checked whenever one is checked. Such as, how do I know a person clicked on the third row checkbox?
you create your column with a DataGridViewCheckBoxColumn control type, and use the Click events and CellContentClick, see example below
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
}
}
}
Regards
Based on what you stated, it's not the Checkboxes which will perform the PostBack, but some other button, So you can check your whole selection at once. In that case, Checkboxes should not be AutoPostBack="true"
.
That said, your Button's code would be something like this:
foreach (GridViewRow row in gv.Rows)
{
CheckBox cb = row.FindControl("cb") as CheckBox;
if (cb != null)
{
if(cb.Checked)
{
//Do your thing here
}
}
}
Update
OP (Justin) posted that he wants to update DB for each CheckBox click. In that case, the solution is handle the CheckBox's OnCheckedChanged
event:
Aspx Code:
<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# Code Behind:
protected void cb_CheckedChanged(object sender, EventArgs e)
{
Checkbox cb = sender as CheckBox;
string yourID = cb.Attributes["yourID"];
//Do your thing
}
精彩评论