异常详细信息: System.ArgumentException: 该行已经属于此表。
Code
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
int i;
dt.Columns.Add(new DataColumn("int", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("string", typeof(System.String)));
dt.Columns.Add(new DataColumn("datatime", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("boolean", typeof(System.Boolean)));
for (i = 0; i < 9; i++)
{
dr[0] = i;
dr[1] = "item" + i.ToString();
dr[2] = System.DateTime.Now.ToShortDateString();
if (i / 2 == 0)
{
dr[3] = true;
}
else
{
dr[3] = false;
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
修改后:
Code
DataTable dt = new DataTable();
int i;
dt.Columns.Add(new DataColumn("int", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("string", typeof(System.String)));
dt.Columns.Add(new DataColumn("datatime", typeof(System.DateTime)));
dt.Columns.Add(new DataColumn("boolean", typeof(System.Boolean)));
for (i = 0; i < 9; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = "item" + i.ToString();
dr[2] = System.DateTime.Now.ToShortDateString();
if (i / 2 == 0)
{
dr[3] = true;
}
else
{
dr[3] = false;
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
实例化行应该放在循环当中。另外,在实例化一个行时候不能用new DataRow();而用dt.NewRow();