列<列名>不属于表 [英] Column <column name> does not belong to table

查看:315
本文介绍了列<列名>不属于表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL中创建了一个包含3个字段的表。并添加了一些数据。现在,我想通过编码将更多数据插入该表。
如果单击button_1,数据将插入表中。
我用下面给出的代码尝试过。

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.

我已经执行了下面给出的查询,但是它显示了一个错误:
Column'Site Name '不属于表
列'SiteId'不属于表
列'集群'不属于表

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");
    }


推荐答案

错误的原因是您试图将具有三个字段的 DataRow 添加到当前不包含任何 DataColumn 的表中。如果要手动执行此操作,则必须使用 dt.Columns.Add(...)

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");

如果表已被填充,并且您想手动添加一些行(如注释中所述),可以使用 SetField 来仅填充某些列:

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");

如果要从数据库中填充它,可以使用 DataAdapter.Fill (表),fe:

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
}

这篇关于列<列名>不属于表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆