Reputation: 501
Gridview with a select-button, a boundfield and a checkbox. Binding the data to the gridview works fine. (the data in the DB has an NVARCHAR column for the bounfield and a BIT column for the checkbox.
When selecting a row via the 'Select' button, an event in code-behind is fired, and data from the 2 cells from the gridview are copied to 2 controls on the page: a textbox and checkbox.
The first works ok and I have no clue as to how to check if the checkbox in the gridview is checked or not. I need to know that so that I can populate other checkbox control accordingly.
(before I paste my code: I just spent some 12 hours searching for a solution here in SO and elsewhere. None of the numerous entries helped. So please bear with me...)
<asp:GridView ID="grv_Test1" runat="server" CssClass="myGrid"
AutoGenerateColumns="False" DataKeyNames="Test1_First_Name"
OnRowCommand="grv_Test1_RowCommand">
<Columns>
<asp:CommandField SelectText="sel'" ShowSelectButton="True" ControlStyle-CssClass="btn btn-primary myBtn-xs">
</asp:CommandField>
<asp:BoundField DataField="Test1_First_Name" HeaderText="Name"><HeaderStyle Width="85px" />
</asp:BoundField>
<asp:CheckBoxField DataField="Test1_Active" HeaderText="Active">
</asp:CheckBoxField>
</Columns>
<HeaderStyle CssClass="myGridHeader" />
</asp:GridView>
Code behind:
int my_Data_From_Grid = Convert.ToInt32(e.CommandArgument);
txb_Test1_Name.Text = grv_Test1.Rows[my_Data_From_Grid].Cells[1].Text; // this works
cbx_Test1_Active.Text = grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text; // NOT working
if (Convert.ToString(grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text) == "1") // NOT working either
{ cbx_Test1_Active.Checked = true; }
else
{ cbx_Test1_Active.Checked = false; }
if (Convert.ToString(grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text) == "True") // NOT working either
{ cbx_Test1_Active.Checked = true; }
else
{ cbx_Test1_Active.Checked = false; }
Here is what I got when selecting Michael's row:
In the gridview Michael is "Active", and I need the checkbox at the top to be 'checked'.
How can it be done...? Thnaks a lot.
Upvotes: 3
Views: 9614
Reputation: 61
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = ((CheckBox)e.Row.FindControl("WasAudited"));
if (chkSelect.Checked)
chkSelect.Enabled = false;
}
}
Upvotes: 0
Reputation: 3949
With CheckBoxFields and CheckBoxes, you need to get the Checked
value to know whether or not it was actually checked. The Text
value is actually another property of the CheckBox (see MSDN). You sometimes see this text to the left or right of the CheckBox itself.
So what you need to do is first get the CheckBox. Then use the Checked
property of that CheckBox.
CheckBox checkBox = (CheckBox)grv_Test1.Rows[my_Data_From_Grid].Cells[2].Controls[0];
cbx_Test1_Active.Checked = checkBox.Checked;
Upvotes: 3