C# checkbox - what am I doing wrong?

  • Thread starter Thread starter Joe Bloggs
  • Start date Start date
J

Joe Bloggs

Anyone know why the code below does not work. All I want is to check a
checkbox, then hit a button, then for the value of the DataKeyField in
the DataGrid to show up as the Text property in a Label. The DataGrid is
working OK as if the foreach loop, the bit where its coming unstuck is
the check box definition or test to see if it is checked. I don't get a
compilation error - just that it doesn't work.

<asp:DataGrid id="DataGrid1" DataKeyField="RequestID" runat="server"
Font-Size="X-Small">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="checkboxSelect"
Runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>

</asp:DataGrid>


private void Button1_Click(object sender, System.EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach(DataGridItem DGridItem in DataGrid1.Items)
{

CheckBox myCheckbox =
(CheckBox)DGridItem.FindControl("checkboxSelect");

if(myCheckbox.Checked == true)
{
sb.Append(DataGrid1.DataKeys[DGridItem.ItemIndex].ToString());
}
}
Label.Text = sb.ToString();
}
 
Guess the check boxes are getting reset everytime the page is called
back. In your page Page_Load method, are you checking if the page is a
postback?

HTH,
-Azhagan
 
Hi,

Are you finding the checkbox?
If not you will get an exception in the if

if you find it and it's never checked then they are not keeping the status,
check if you do a databind() in a postback, if so you have to change it
like this:

void Page_Load(... )
{
if ( !IsPostBack )
this.DataBind();
}

Cheers,
 
Hi - yes I was missing the IsPostBack check on my Page_Load method.
Thank you for your help.
 
Back
Top