Column does not belong to table

2020-04-17 05:20发布

问题:

I have created a table with 3 field in SQL. And added some data. Now I want to insert more data into that table by coding. If I click button_1 the data are to be inserted into table. I tried by this given below code.

I have executed the given below query, but it shows an error: "Column 'Site Name' does not belong to table" "Column 'SiteId' does not belong to table" "Column 'Cluster' does not belong to table"

protected void Button1_Click(object sender, EventArgs e)
    {
        string strcon = WebConfigurationManager.ConnectionStrings["insertBulkConnectionString"].ConnectionString;
        DataTable dt = new DataTable();
        DataRow rowAdded = dt.Rows.Add(); 
        rowAdded.SetField("SiteName", "A");
        rowAdded.SetField("State", "B");
        rowAdded.SetField("Cluster", "C");
    }

回答1:

The reason for the error is that you're trying to add a DataRow with three fields to a table that currently doesn't contain any DataColumns. You have to use dt.Columns.Add(...) if you want to do that manually.

DataTable dt = new DataTable();
dt.Columns.Add("SiteName", typeof(string));
dt.Columns.Add("State", typeof(string));
dt.Columns.Add("Cluster", typeof(string));
dt.Rows.Add("A", "B", "C");

If the table was already filled and you want to add some rows manually(as mentioned in comment) you could use SetField to fill only some of the columns:

DataRow rowAdded =  dt.Rows.Add(); // already added at this point with empty fields
rowAdded.SetField("SiteName", "A");
rowAdded.SetField("State", "B");
rowAdded.SetField("Cluster", "C");

If you want to fill it from the database you can use DataAdapter.Fill(table), f.e:

using(var con = new SqlConection(WebConfigurationManager.ConnectionStrings["insertBulkConnectionString"].ConnectionString))
using(var da = new SqlDataAdapter("SELECT * FROM Table ORDER BY Column", con))
{
    da.Fill(dt);  // you don't need to add the columns or to open the connection
}