C# 中 foreach 循环迭代中的列不属于数据表。我正在将行记录插入到数据表中,但是面对的列不属于数据表。//Prepare Datatable and Add All Columns Here DataTable dt = new DataTable(); DataRow row; DataColumn dc = new DataColumn(); dc.DataType = System.Type.GetType("System.String"); dc.ColumnName = "title"; dc.ReadOnly = false; dc.Unique = true; dc.AutoIncrement = false; dc.DataType = System.Type.GetType("System.String"); dc.ColumnName = "link"; dc.ReadOnly = false; dc.Unique = true; dc.AutoIncrement = false; foreach (XmlNode rssNode in rssNodes) { XmlNode rssSubNode = rssNode.SelectSingleNode("title"); string title = rssSubNode != null ? rssSubNode.InnerText : ""; rssSubNode = rssNode.SelectSingleNode("link"); string link = rssSubNode != null ? rssSubNode.InnerText : ""; //Add new row and assign values to columns, no need to add columns again and again in loop which will throw exception row = dt.NewRow(); //Map all the values in the columns row["title"] = title; row["link"] = link; //At the end just add that row in datatable dt.Rows.Add(row); }
1 回答
富国沪深
TA贡献1790条经验 获得超9个赞
在设置每一列之前,您需要调用dc = new DataColumn();对第一列而不是第二列所做的操作。设置好列的所有参数后,需要将其添加到表中dt.Columns.Add(dc);。
DataColumn dc;
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "title";
dc.ReadOnly = false;
dc.Unique = true;
dc.AutoIncrement = false;
dt.Columns.Add(dc);
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = "link";
dc.ReadOnly = false;
dc.Unique = true;
dc.AutoIncrement = false;
dt.Columns.Add(dc);
- 1 回答
- 0 关注
- 110 浏览
添加回答
举报
0/150
提交
取消