I have a function with the following code that binds a table dynamically. I am calling this function in the page load. After this method is called the table contains three columns: A checkbox, label, and textbox.
I also have a button control. When this button is clicked I am checking for the checked checkboxes inside the table and then inserting data into the database corresponding to checked checkbox.
The problem is that it is not storing the checked state of the checkbox when the button is clicked as the button click also calls page load, which calls the function below and hence all of the elements in the table are recreated.
I cant use Page.IsPostBack here because the table should be loaded when the button is clicked. If I write the below code inside if(!Page.IsPostBack) then on button click it is not finding any rows in the table
try
{
ManageVIN objMngVin = new ManageVIN();
DataTable tblVins = objMngVin.MyFunction(clientCode);
if (tblAssociateFleet.Rows.Count > 1)
{
for (int i = 1; i <= tblAssociateFleet.Rows.Count - 1; i++)
{
tblAssociateFleet.Rows[i].Cells.Clear();
}
}
if (tblVins != null && tblVins.Rows.Count > 0)
{
foreach (DataRow dr in tblVins.Rows)
{
HtmlTableRow tblRow = new HtmlTableRow();
tblRow.Attributes.Add("class", "tblrow");
HtmlTableCell tblCell1 = new HtmlTableCell();
CheckBox chk = new CheckBox();
chk.CssClass = "selctChk";
if (!Page.IsPostBack)
{
chk.Checked = false;
}
tblCell1.Controls.Add(chk);
HtmlTableCell tableCelll2 = new HtmlTableCell();
Label lblVinVlaue = new Label();
lblVinVlaue.Text = Convert.ToString(dr["VIN"]);
tableCelll2.Controls.Add(lblVinVlaue);
HtmlTableCell tableCell3 = new HtmlTableCell();
TextBox txtVinVal = new TextBox();
txtVinVal.CssClass = "textEntry";
tableCell3.Controls.Add(txtVinVal);
tblRow.Cells.Add(tblCell1);
tblRow.Cells.Add(tableCelll2);
tblRow.Cells.Add(tableCell3);
tblAssociateFleet.Rows.Add(tblRow);
}
}
}
How can I deal with this problem?
You should do this in the Init or PreInit life cycle. PreInit is the preferred place for this according to MS. If you take a look at the ASP.NET page life cycle Load is a bit too late (specifically missing IPostBackDataHandler.LoadPostData which processes postback data of your checkbox clicks).
Also, this is similiar to this stack overflow question.