WPF如何从DataGrid转换为DataTable?

时间:2016-05-29 21:46:57

标签: wpf datatable casting datagrid

您好我正在关注此guide以了解如何使用DataGrid。

我遇到的问题是如何将数据从DataGrid转换为DataTable?

我正在尝试的代码是:

DataTable dt = ((DataView)dg.ItemsSource).ToTable();

但它给出了一个错误说明:

  

无法投射类型的对象   'System.Collections.Generic.List`1 [WPFProject.Person]'输入   'System.Data.DataView'。

我的代码与示例非常相似,只是我使用Person而不是user,我创建了一个Person类型的列表,以便将数据插入到datagrid中。

public class Person
    {
        public bool CheckBox { get; set; }
        public int ID { get; set; }
        public string Name { get; set; }
    }

谢谢。

4 个答案:

答案 0 :(得分:1)

你不能这样转换它。只有ItemSource的{​​{1}}不是DataGrid时,您的代码才有效。您需要明确编写代码(您可以轻松地将其搜索到 DataViewcollection<T> )以将DataTable转换为collection。看看下面的例子:

<强> XAML

DataTable

<强> 逻辑:

  <StackPanel>
    <DataGrid ItemsSource="{Binding list}" x:Name="myGrid"/>
    <Button Content="convert back" Click="Button_Click_1" />
</StackPanel>

<强> 输出

Grid

DataTable

答案 1 :(得分:0)

你不能像在winforms中那样在WPF中这样做。在Wpf中,您可以像这样在dataTable中设置datagrid ItemsSource。

dg.ItemsSource = dataTable.AsDataView();

在您的情况下,您希望从 datagrid 获取 dataTable 。 所以你可以试试下面的代码。

DataView view = (DataView) dg.ItemsSource;
DataTable dataTable = view.Table.Clone();
foreach (var dataRowView in view)
{
    dataTable.ImportRow(dataRowView.Row);
}
var dataTableFromDataGrid = dataTable;

答案 2 :(得分:0)

要将DataGrid转换为DataTable

1.DataGrid项源与CandidateClass列表绑定。

2。从DataGrid的Itemsource获取该Item,然后将其序列化为Json并作为DataTable反序列化。

  var Item = ListDataGrid.ItemsSource as IList<CandidateClass>;
  var json = JsonConvert.SerializeObject(Item);
  DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

注意:如果DataGrid是基于类对象列表形成的,则此方法很有帮助。

答案 3 :(得分:0)

复制过去的方法1

public static DataTable DataGridtoDataTable(DataGrid dg)
        {
dg.SelectAllCells();
            dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
            ApplicationCommands.Copy.Execute(null, dg);
            dg.UnselectAllCells();
            String result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
            string[] Lines = result.Split(new string[] { "\r\n", "\n" }, 
            StringSplitOptions.None);
            string[] Fields;
            Fields = Lines[0].Split(new char[] { ',' });
            int Cols = Fields.GetLength(0);
            DataTable dt = new DataTable();
            //1st row must be column names; force lower case to ensure matching later on.
            for (int i = 0; i < Cols; i++)
                dt.Columns.Add(Fields[i].ToUpper(), typeof(string));
            DataRow Row;
            for (int i = 1; i < Lines.GetLength(0)-1; i++)
            {
                Fields = Lines[i].Split(new char[] { ',' });
                Row = dt.NewRow();
                for (int f = 0; f < Cols; f++)
                {
                    Row[f] = Fields[f];
                }
                dt.Rows.Add(Row);
            }
            return dt;
            
        }

================================================ =======================================

方法2

public DataTable DataGridtoDataTable(DataGrid dg)
        {

            DataTable dt = new DataTable();

            for (int i = 0; i <= dg.Columns.Count - 1; i++)
            {
                dt.Columns.Add(dg.Columns[i].Header.ToString(), typeof(string));
            }
            DataRow Row;

            for (int i = 0; i <= dg.Items.Count - 1; i++)
            {
                Row = dt.NewRow();

                for (int k = 0; k <= dg.Columns.Count - 1; k++)
                {
                    Row[dg.Columns[k].Header.ToString()] = gettabelcell(i, k,dg);

                }
                dt.Rows.Add(Row);
            }

            return dt;

        }

public String gettabelcell(int x, int y,DataGrid dg)
        {
            try
            {
                String myString = dg.GetCell(x, y).ToString();

                if (myString.Contains(":"))
                {
                    String[] s = myString.Split(':');
                    String item = s[1];
                    return item.Trim();
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }

这是课

static class ExtensionHelpers
   {

       public static T GetVisualChild<T>(Visual parent) where T : Visual
       {
           T child = default(T);
           int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
           for (int i = 0; i < numVisuals; i++)
           {
               Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
               child = v as T;
               if (child == null)
               {
                   child = GetVisualChild<T>(v);
               }
               if (child != null)
               {
                   break;
               }
           }
           return child;
       }

       public static DataGridCell GetCell(this DataGrid grid, int row, int column)
       {
           DataGridRow rowContainer = grid.GetRow(row);
           return grid.GetCell(rowContainer, column);
       }
       public static DataGridRow GetSelectedRow(this DataGrid grid)
       {
           return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
       }
       public static DataGridRow GetRow(this DataGrid grid, int index)
       {
           DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
           if (row == null)
           {
               // May be virtualized, bring into view and try again.
               grid.UpdateLayout();
               grid.ScrollIntoView(grid.Items[index]);
               row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
           }
           return row;
       }

       public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
       {
           if (row != null)
           {
               DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

               if (presenter == null)
               {
                   grid.ScrollIntoView(row, grid.Columns[column]);
                   presenter = GetVisualChild<DataGridCellsPresenter>(row);
               }

               DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
               return cell;
           }
           return null;
       }
   }