I’ve been struggling with a CheckBox column in a GridView in ASP .NET / C#. When finished, this page should display current open positions for my office. People should be able to check as many positions as they’d like to apply for and then continue to the next screen (where the actual application begins).
This is the routine I run when the ‘Apply Now’ button is clicked. I found this code on here after trying about a dozen other combinations suggested by my boss and people on here. When I run it, isChecked = false, so it doesn’t run anything within that if statement. Am I missing something obvious?
for (int i = GridView1.Rows.Count - 1; i > -1; i--)
{
GridViewRow row = GridView1.Rows[i];
bool isChecked = ((CheckBox)row.FindControl("cbx_apply")).Checked;
if (isChecked)
{
try
{
Response.Write("Hello world");
PositionsAppliedFor.Add(Convert.ToInt32((GridView1.Rows[i].Cells[1].Text)));
Session["SelectedPositionIDList"] = PositionsAppliedFor;
}
catch (Exception error)
{
Response.Write(error.Message);
}
}
}
EDIT: Also, I realize the stuff I’m doing within the if statement isn’t anything important.. I’m just trying to get it to do /something/.
ASP.NET:
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="UpdateSelectedPostions">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbx_apply" runat="server"
OnCheckedChanged="UpdateSelectedPostions"
AutoPostBack="false"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Simple, and probably missing a lot. I’m /very/ new to ASP.NET.
This is where I load the data for the grid and bind it:
string sqlstatement = "SELECT * FROM dbo.POSITION WHERE PositionStartDate < GETDATE() AND PositionEndDate > GETDATE()";
command = new SqlCommand(sqlstatement, connection);
ds = new DataSet();
adapter = new SqlDataAdapter(command);
builder = new SqlCommandBuilder(adapter);
adapter.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
connection.Close();
Hopefully this is enough, because it’s really all I have. I haven’t put anything else on the page yet – just trying to get these stupid checkboxes to agree with me.
Make sure your binding code is in a block like this:
Otherwise you’ll be recreating the checkboxes on each postback and therefore losing the fact that they’re checked.