2

How can I fill DataTable from GridView in ASP.NET?

Alex
  • 8,908
  • 28
  • 103
  • 157
  • Check out my suggestion to a similar problem http://stackoverflow.com/questions/785799/how-can-i-export-a-gridview-datasource-to-a-datatable-or-dataset/31617551#31617551 – Muzoora Savior Jul 24 '15 at 18:42

4 Answers4

10

Simply, you can do like this:

BindingSource bindingSource = (BindingSource )yourGridView.DataSource;
DataTable yourDataTable= (DataTable ) bindingSource .DataSource;

Another way, you can do like this:

DataTable yourDataTable = yourGridView.DataSource as DataTable
Akash KC
  • 16,057
  • 6
  • 39
  • 59
  • after filling the grid I add text in two Textboxes, so the source of the grid is not what i need – Alex Aug 15 '12 at 08:51
  • 3
    You need to elaborate your problem more so that we know what you are actually looking for.... – Akash KC Aug 15 '12 at 08:53
3
 I solved like this
           if (myGridView.Rows.Count > 0)
            {
                var dt = new DataTable();
                dt.Columns.Add("Column1", typeof(string));
                dt.Columns.Add("Column2", typeof(Int64));
                dt.Columns.Add("Column3", typeof(string));

                foreach (GridViewRow row in gd_endYearSchool.Rows)
                {
                    var id = row.Cells[1].Text;
         //for find textbox
          var tb1 = row.Cells[2].FindControl("tbNr") as TextBox;
                    int nrord = 0;
                    if (tb1 != null)
                    {
                        var ord = tb1.Text;
                        if (!Int64.TryParse(ord, out nrord))
                        {
                            nrord = 0;
                        }
                    }
                    var text=row.Cell[3].text;
                    dt.Rows.Add(id,nrord,text);
                }

            }
Alex
  • 8,908
  • 28
  • 103
  • 157
1

you can fill datatable from gridview with foreach

csharp
  • 59
  • 4
1

I'll do like this, i think this'll help u.

public void Data_table()
{
    Session["Data"] = "";
    DataTable dt = new DataTable();
    //Add Columns to the datatable
    dt.Columns.Add("c1");
    dt.Columns.Add("c2");
    dt.Columns.Add("c3");
    //Define a datarow for the datatable dt
    DataRow dr = dt.NewRow();
    //Now add the datarow to the datatable
    Session["Data"] = dt;
    RadGrid1.DataSource = dt;
    RadGrid1.Rebind();
}

protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{            
    if (((System.Data.DataTable)(Session["Data"])).Rows.Count.ToString() != "")
    {
        RadGrid1.DataSource = Session["Data"];
    }
}

Thank you..,

SuganR
  • 129
  • 1
  • 10
  • a best practice would be to replace all uses of "" with String.Empty (although some do not appreciate the appearance equally) – Hardryv Aug 09 '13 at 19:02