Domanda

I am trying to add a row acquired from a database to a DataTable.
First I tried Using bucketdt.Rows.Add(r); I got an error saying Row belongs to another Table
Then I used bucketdt.ImportRow(r); then it doesn't copy the row at all!

if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        //DataTable f = new DataTable();
        dosObject = new DataOperations();
        bucketdt = new DataTable();
        count=0;
        foreach (string key in Session.Keys)
        {
            string val = Session[key].ToString();
            DataRow r = bucketdt.NewRow();
            r = dosObject.SubCategoryDetails2(Convert.ToInt16(val)).Rows[0];
            bucketdt.ImportRow(r);
            bucketdt.AcceptChanges();
        }
        GridView1.Enabled = true;
        GridView1.DataSource = bucketdt;
        GridView1.DataBind();
    }
    else
        Response.Redirect(FormsAuthentication.LoginUrl);

am I missing something?

Now I tried adapting the code as told by @wonko79

 DataTable f = new DataTable();
        dosObject = new DataOperations();
        bucketdt = new DataTable();
        count=0;
        foreach (string key in Session.Keys)
        {
            string val = Session[key].ToString();

            DataRow r = bucketdt.NewRow();
            f = dosObject.SubCategoryDetails2(Convert.ToInt16(val));
            r["Id"]=f.Rows[0].ItemArray[0].ToString();
            r["SubCategoryName"] = f.Rows[0].ItemArray[1].ToString();
            r["Make"] = f.Rows[0].ItemArray[2].ToString();
            r["Cost"] = f.Rows[0].ItemArray[3].ToString();
            //bucketdt.ImportRow(r);
            bucketdt.Rows.Add(r);
            bucketdt.AcceptChanges();

n now it says the row doesnt contain Column: 'Id' does not belong to table .

È stato utile?

Soluzione

You are overwriting your DataRow r which follows the schema of bucketdt with a DataRow folowing another schema.

DataRow r = bucketdt.NewRow();
        r = dosObject.SubCategoryDetails2(Convert.ToInt16(val)).Rows[0]; // overwrites r with a DataRow following another schema
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top