【问题标题】:Convert present Datagrid data into DataTable将当前 Datagrid 数据转换为 DataTable
【发布时间】:2012-10-18 07:48:45
【问题描述】:

如何将现有的Datagrid数据转换成DataTable?我已经过滤了数据网格,现在我只想过滤数据到数据表中。 Datagrid.ItemSource 或 DatagridView 在这里没有帮助。

【问题讨论】:

  • 数据的原始来源是什么?即 DataGrid 绑定到什么?
  • 什么返回datagrid1.ItemsSource.GetType().Name;
  • 你使用的是什么 ASP.net 或 Winform 应用程序?

标签: c# wpf datagrid datatable


【解决方案1】:

您可以将数据从 datagrid 放到 datatble 中:

        DataTable dt = new DataTable();  
        DataColumn[] dcs = new DataColumn[]{};  

        foreach (DataGridViewColumn c in dgv.Columns)  
        {  
            DataColumn dc = new DataColumn();  
            dc.ColumnName = c.Name;  
            dc.DataType = c.ValueType;  
            dt.Columns.Add(dc);  

        }  

        foreach (DataGridViewRow r in dgv.Rows)  
        {  
            DataRow drow = dt.NewRow();  

            foreach (DataGridViewCell cell in r.Cells)  
            {  
                drow[cell.OwningColumn.Name] = cell.Value;  
            }  

            dt.Rows.Add(drow);  
        }  

【讨论】:

  • 我只有数据网格。我没有 datagridview。
  • 我这里没有 dgv。想要将现有的数据网格项目转换为数据表
【解决方案2】:

将更新后的数据保存在会话中,或者将其写入 XML 并随时获取数据。

类似的东西

 private void BindGrid()
    {
        DataTable dt;
        if (Session["GridData"] == null)
        {
            dt = GetData();//From database or and other source
            Session["GridData"] = dt;
        }
        else
        {
            dt = (DataTable)Session["GridData"];
        }

        GridView.datasource = dt;
        GridView.Databind();
    }

    private void UpdataData(object sender, EventArgs e)
    {
        DataTable dt;
        if (Session["GridData"] != null)
        {
            dt = (DataTable)Session["GridData"];


        // Do whatever you want with dt (datatable);
        Session["GridData"] = dt;

        BindGrid();
       }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多