簡體   English   中英

在 WPF DataGrid 中轉換和使用 DataTable?

[英]Convert and use DataTable in WPF DataGrid?

在普通的 WinForm 應用程序中,您可以這樣做:

DataTable dataTable = new DataTable();
dataTable = dataGridRecords.DataSource;

但是如何使用 WPF 數據網格來做到這一點?

dataTable = dataGridRecords.ItemsSource;

也不會工作。

在 WPF 中你不這樣做

DataGrid.ItemsSource = DataTable;

相反,你做

 DataGrid.ItemsSource = DataTable.AsDataView();

為了讓 DataTable 回來,你可以做這樣的事情

public static DataTable DataViewAsDataTable(DataView dv)
{
    DataTable dt = dv.Table.Clone();
    foreach (DataRowView drv in dv)
       dt.ImportRow(drv.Row);
    return dt;
}

DataView view = (DataView) dataGrid.ItemsSource;
DataTable table = DataViewAsDataTable(view)

您不需要DataViewAsDataTable方法。 只需執行以下操作:

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

嘗試這個

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

    }

如果我們只需要將DataGrid.ItemsSource轉換為DataView一次,我使用.NET Framework 4.5.2測試的第一個和第二個選項可以正常工作,但如果我們需要一次執行多次,我們會收到以下錯誤:

System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List 1[System.Object]' to type 'System.Data.DataView'.' 亂序

為了將DataGrid.ItemsSource轉換為DataTable ,我在各種情況下嘗試了以下解決方案,每種方案都有優點和缺點(我花了幾個月的時間研究和測試):

此鏈接將向您展示每種方法的優缺點

我認為最好的方法是使用CollectionViewSource

C#:

    uint[] BookCodeSelectedItems = null; //This command is for example only
    CollectionViewSource BookCollectionViewSource = new CollectionViewSource();
    public MainWindow()
    {
        InitializeComponent();
        BookCollectionViewSource.Source = BookDataGrid.ItemsSource; //It is assumed that "BookDataGrid.ItemsSource" is already filled up.
    }
    private void DataGridDeleteMenu_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        List<object> Row = new List<object>();
        //Additionally, I tested the "AddRange" function of the "List<>" and it appeared to be one second slower. I mean "Row.AddRange(BookDataGrid.Items.Cast<object>().ToList());"
        for (int i = 0; i < BookDataGrid.Items.Count; i++)
        {
            Row.Add(BookDataGrid.Items[i]);
        }
        DataView DV = BookCollectionViewSource.Source as DataView;
        DataTable DT = DV.Table;
        BookCodeSelectedItems = new uint[BookDataGrid.SelectedItems.Count]; //I need this for further calculations
        for (int i = 0; i < BookDataGrid.SelectedItems.Count; i++)
        {
            BookCodeSelectedItems[i] = uint.Parse(DT.Rows[i][3].ToString());
            Row.Remove(BookDataGrid.SelectedItems[i]);
        }
        BookDataGrid.ItemsSource = Row;
    }

輸出: 輸出

測試:

Visual Studio 2017 , .NET Framework 4.5.2 , WPF

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM