将当前的Datagrid数据转换为DataTable

时间:2012-10-18 07:48:46

标签: c# wpf datagrid datatable

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

2 个答案:

答案 0 :(得分:2)

您可以将数据从datagrid放到datatable asp>

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

答案 1 :(得分:1)

在会话中保留更新的数据或将其写入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();
       }

    }