Requirement was to add new row data to gridview from textbox. The data populated in the gridview was from a datatable and not in a DB.
Problem occurred when the datatable was static the following error appeared "A column named 'columnname' already belongs to this DataTable." This was because after a record is saved the pageLoad event is triggered and under pageLoad we had created ColumnNames. So, the error popped up when we tried to add the same column name over and over again.
Solution was to declare the datatable as static so that the old rows are saved and not overwritten and also to check if the no. of columns in the table is not zero which will indicate that the datatable is already created.
Problem occurred when the datatable was static the following error appeared "A column named 'columnname' already belongs to this DataTable." This was because after a record is saved the pageLoad event is triggered and under pageLoad we had created ColumnNames. So, the error popped up when we tried to add the same column name over and over again.
Solution was to declare the datatable as static so that the old rows are saved and not overwritten and also to check if the no. of columns in the table is not zero which will indicate that the datatable is already created.
static DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (dt.Columns.Count==0)
{
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("age", typeof(int));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
dt.Rows.Add(TextBox1.Text, Convert.ToInt32(TextBox2.Text));
GridView1.DataSource = dt;
GridView1.DataBind();
}
No comments:
Post a Comment