C# checkbox - what am I doing wrong?

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();
}
 
A

Azhagan

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
 
I

Ignacio Machin \( .NET/ C# MVP \)

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,
 
J

Joe Bloggs

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top