在C#中从GridView填充DataTable

时间:2012-08-15 08:38:30

标签: c# asp.net gridview datatable

如何从ASP.NET中的GridView填充DataTable?

4 个答案:

答案 0 :(得分:10)

简单地说,你可以这样做:

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

另一种方式,你可以这样做:

DataTable yourDataTable = yourGridView.DataSource as DataTable

答案 1 :(得分:2)

 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);
                }

            }

答案 2 :(得分:1)

您可以使用foreach

从gridview填充数据表

答案 3 :(得分:1)

我会这样做,我想这会对你有帮助。

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"];
    }
}

谢谢..,