user6592730 user6592730 - 3 months ago 10
ASP.NET (C#) Question

How to solve Column 'Policy_No' does not belong to table?

I have a simple interface which has a text box, button and a gridview. I want to display the number in the gridview when click the button. But I get an ArgumentException saying "Column 'Policy_No' does not belong to table". what should I do to solve it. Here I have added the code below.

Button Click Event

protected void btnAdd_Click(object sender, EventArgs e)
{
dt = new DataTable();
dr = dt.NewRow();
dr["Policy_No"] = txtPolicy.Text.Trim();
dt.Rows.Add(dr);
grdPolicy.DataSource = dt;
grdPolicy.DataBind();
}


Page Load code

protected void Page_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Policy_No", typeof(string)));
if (!IsPostBack)
{
loadCompetitionsNames();

}
}

Answer

You are creating new DataTable inside btnAdd_Click that doesn't have column Policy_No

protected void btnAdd_Click(object sender, EventArgs e)
{
        //dt = new DataTable();   Remove this line
        dr = dt.NewRow();
        dr["Policy_No"] = txtPolicy.Text.Trim();
        dt.Rows.Add(dr);
        grdPolicy.DataSource = dt;
        grdPolicy.DataBind();
}
Comments