运行时错误找不到列0.以下是我的代码
string connectiostring = (string)ConfigurationSettings.AppSettings["NorthwindConnectionString"];
SqlConnection conn = new SqlConnection(connectiostring);
SqlCommand cmd = new SqlCommand("select * from Employees", conn);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
adapter.Fill(data,"Employees");
data.Tables["Employees"].Columns.Add("Testcolumn");
DataTable t1 = new DataTable("Employees");
DataRow newrow = t1.NewRow();
newrow[0] = "10";\\this the line i am getting error
newrow[1] = "Pradeep";
newrow[2] = "Kumar";
data.Tables["Employees"].Rows.Add(newrow);
GridView2.DataSource = data;
GridView2.DataBind();
请帮帮我 谢谢,
答案 0 :(得分:6)
您尚未将列添加到DataTable
。
t1.Columns.Add(new DataColumn
{
DataType = string,
ColumnName = "First Name"
});
为每个列重复此操作,为每个列提供正确的类型。
答案 1 :(得分:4)
创建一个在尝试添加行之前添加列的函数。在InitializeComponents中调用方法..
ex.
private void InitTbl(DataTable myTbl)
{
myTbl.Columns.Add(new DataColumn("id"));
myTbl.Columns.Add(new DataColumn("fname"));
myTbl.Columns.Add(new DataColumn("lname"));
}
答案 2 :(得分:2)
您需要先在表格中添加一些列:
DataTable t1 = new DataTable("Employees");
t1.Columns.Add("column1", typeof(string));
t1.Columns.Add("column2", typeof(string));
t1.Columns.Add("column3", typeof(string));
DataRow newrow = t1.NewRow();
...
答案 3 :(得分:1)
我想也许这实际上是你的问题。
DataTable t1 = new DataTable("Employees")
这会创建一个不属于数据集的全新表格对象。
所以你应该用这个替换它
DataTable t1 = data.Tables["Employees"]
从数据集中获取表并将t1变量指向该表。