I am binding some Data in the Page_load method in GridView1. I have a checkBox CheckBox1. After checking the checkboxes i want to display something(As a test) in the Label1 when i press a button . But it is not showing. I am not Binding Data with SQLDatasource rather i am binding it manually.
My Page_load method
protected void Page_Load(object sender, EventArgs e)
{
string[,] arrMultiD = {
{ "John", "21", "Berlin", "Germany" },
{ "Smith", "33" ,"London", "UK"},
{ "Ryder", "15" ,"Sydney", "Australia"},
{ "Jake", "18", "Tokyo", "Japan"},
{ "Tom","34" , "Mumbai", "India"}
};
DataTable dt = new DataTable();
dt.Columns.Add("Name", Type.GetType("System.String"));
dt.Columns.Add("Age", Type.GetType("System.String"));
dt.Columns.Add("City", Type.GetType("System.String"));
dt.Columns.Add("Country", Type.GetType("System.String"));
for (int i = 0; i < 5; i++)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["Name"] = arrMultiD[i, 0];
dt.Rows[dt.Rows.Count - 1]["Age"] = arrMultiD[i, 1];
dt.Rows[dt.Rows.Count - 1]["City"] = arrMultiD[i, 2];
dt.Rows[dt.Rows.Count - 1]["Country"] = arrMultiD[i, 3];
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
My Button Click function
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb != null && cb.Checked)
{
Label1.Text += "1";
}
}
}
I have checked in debug mode. When i was clicking the button, the if portion was not being executed. It is as if the Data in the GridView was lost as soon as i clicked the button. In other words GridView lost its data when it was out of Page_Load method
my aspx code
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True">
<Columns>
<asp:TemplateField HeaderText="dd">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>