gpt4 book ai didi

c# - 将 NameValueCollection 插入到数据表中,这会给我一些错误,例如 This row already belongs to this table

转载 作者:行者123 更新时间:2023-11-30 22:22:12 27 4
gpt4 key购买 nike

asp.net 和 C# 的新手,如有帮助将非常感谢。

我的代码

protected void Button1_Click(object sender, EventArgs e)
{
string x = "item_name1=number1&item_number1=product1";
NameValueCollection key = HttpUtility.ParseQueryString(x);
DataTable Theproducts = new DataTable();

Theproducts.Columns.Add("ProductID");
Theproducts.Columns.Add("ProductName");
DataRow row = Theproducts.NewRow();
int index = 1;
foreach(string keys in key.AllKeys)
{
if (keys == ("item_number" + index.ToString()))
{
row["ProductID"] = key[keys];
}
if (keys == ("item_name" + index.ToString()))
{
row["ProductName"] = key[keys];
}
Theproducts.Rows.InsertAt(row, 0);
}
GridView1.DataSource = Theproducts;
GridView1.DataBind();
}//end of button

获取错误此行已属于此表。

最佳答案

您需要将 DataRow 声明移动到 foreach 循环中。

foreach(string keys in key.AllKeys)
{
DataRow row = Theproducts.NewRow();
if (keys == ("item_number" + index.ToString()))
{
row["ProductID"] = key[keys];
}
if (keys == ("item_name" + index.ToString()))
{
row["ProductName"] = key[keys];
}
Theproducts.Rows.InsertAt(row,0);
}

当前,您正在 foreach 循环之外 创建 DataRow 对象,并且在每次迭代中您都试图将相同的对象插入到数据表中。这就是您收到错误的原因。

关于c# - 将 NameValueCollection 插入到数据表中,这会给我一些错误,例如 This row already belongs to this table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13968322/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com