Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to save a GridView to a DataTable.

I have code which should in theory do it but I keep getting this error:

Column 0 doesn't exist

Here is my code:

protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        for (int j = 0; j < GridView1.Rows.Count; j++)
        {
            DataRow dr;
            GridViewRow row = GridView1.Rows[j];
            dr = dt.NewRow();
            for (int i = 0; i < row.Cells.Count; i++)
            {
                dr[i] = row.Cells[i].Text;
            }

            dt.Rows.Add(dr);
        }
    }

Any help on how to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

you can do something like this:

DataTable dt = new DataTable();
for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        dt.Columns.Add("column"+i.ToString());
    }
foreach (GridViewRow row in GridView1.Rows)
    {
        DataRow dr = dt.NewRow();
        for(int j = 0;j<GridView1.Columns.Count;j++)
            {
                dr["column" + j.ToString()] = row.Cells[j].Text;
            }

            dt.Rows.Add(dr);
    }

And that will show that it works.

GridView6.DataSource = dt;
GridView6.DataBind();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...