Column does not belong to table

后端 未结 1 1855
陌清茗
陌清茗 2021-01-22 03:32

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

1条回答
  •  滥情空心
    2021-01-22 04:11

    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
    }
    

    0 讨论(0)
提交回复
热议问题