简体   繁体   English

向数据表添加新行时出现错误

[英]While Adding new row to Data Table getting an Error

I want to make stacked area chart in Run Time.我想在运行时制作堆积面积图。 I want to add datapoints when i click button.我想在单击按钮时添加数据点。

However getting an error ' this row already belongs to another table '.但是收到错误“此行已属于另一个表”。

Here is the full code of Simple Project;这是 Simple Project 的完整代码;

DataRow drIBM, drMSN, drMCN;
DataTable chartData = new DataTable();
Random r = new Random();
int count = 0;

protected void Page_Load(object sender, EventArgs e)
{
    chartData.Columns.Add("Series Label", typeof(string));

    for (int i = 0; i < 10; i++)
    {
        chartData.Columns.Add("DP_" + i.ToString(), typeof(int)); // Addind Datapoints as a Columns
    }

    drIBM = chartData.NewRow();
    drMSN = chartData.NewRow();
    drMCN = chartData.NewRow();

    drIBM["Series Label"] = "IBM";
    drMSN["Series Label"] = "MSN";
    drMCN["Series Label"] = "MCN";

    if (Session["chartData"] == null)
    {
        Session["chartData"] = chartData;
    }

}

protected void Button1_Click(object sender, EventArgs e)
{
    count++;

    chartData = Session["chartData"] as DataTable;

    drIBM[count] = r.Next(1, 10); // Datarow[Column Index] getting random number
    drMSN[count] = r.Next(1, 10);
    drMCN[count] = r.Next(1, 10);

    chartData.Rows.Add(drIBM); // In this part I am getting above error.
    chartData.Rows.Add(drMSN);
    chartData.Rows.Add(drMCN);

    Session["chartData"] = chartData;
    UltraChart1.DataSource = Session["chartData"];
    UltraChart1.DataBind();
}

I'm not hugely familiar with the inner workings of the DataRow class but I'm guessing it holds a reference to chartData at the time you call chartData.NewRow();我不太熟悉DataRow类的内部工作原理,但我猜它在您调用chartData.NewRow();时保存了对chartData的引用chartData.NewRow();

In Button1_Click() you are replacing this reference with one to an object held in your Session object.Button1_Click()您将此引用替换为对Session对象中保存的对象的引用。 Even though semantically identical to chartData , the DataRow believes this is a different object and thus throws the exception.尽管在语义上与chartData相同,但DataRow认为这是一个不同的对象,因此抛出异常。

Considering chartData seems to be a class variable, I'm not sure why you are bothering with Session at all.考虑到chartData似乎是一个类变量,我不知道你为什么要打扰Session Try removing the following line and see if this works:尝试删除以下行,看看这是否有效:

chartData = Session["chartData"] as DataTable;

You have declared Row variables globally.您已全局声明 Row 变量。 If you change the scope of these variable to local ie remove the declaration of these DataRow variables from the top and declare those again in methods.(eg declare DataRow drIBM, drMSN, drMCN; in specific methods like Page_Load and Button_Click1) should solve the issue.如果您将这些变量的范围更改为本地,即从顶部删除这些 DataRow 变量的声明并在方法中再次声明。(例如声明 DataRow drIBM、drMSN、drMCN;在特定方法中,如 Page_Load 和 Button_Click1)应该可以解决问题.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM