【问题标题】:Filling DataTable from GridView in C#在 C# 中从 GridView 填充数据表
【发布时间】:2012-08-11 13:41:52
【问题描述】:

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

【问题讨论】:

标签: c# asp.net gridview datatable


【解决方案1】:

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

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

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

DataTable yourDataTable = yourGridView.DataSource as DataTable

【讨论】:

  • 填充网格后,我在两个文本框中添加了文本,所以网格的来源不是我需要的
  • 您需要详细说明您的问题,以便我们知道您真正在寻找什么......
【解决方案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);
                }

            }

【讨论】:

    【解决方案3】:

    您可以使用 foreach 从 gridview 填充数据表

    【讨论】:

      【解决方案4】:

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

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

      谢谢你..,

      【讨论】:

      • 最好的做法是用 String.Empty 替换 "" 的所有用法(尽管有些人不喜欢这种外观)
      猜你喜欢
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多