【问题标题】:How Bind DataTable to DataGrid如何将 DataTable 绑定到 DataGrid
【发布时间】:2011-10-12 02:24:39
【问题描述】:

这是我的数据表。

DataTable _simpleDataTable = new ataTable();     

var person = new DataColumn("Person") {DataType = typeof (Person)};
_simpleDataTable.Columns.Add(person);

var student = new DataColumn("Student") {DataType = typeof (Student)};
_simpleDataTable.Columns.Add(student);

 var dr1 = _simpleDataTable.NewRow();
dr1[0] = new Person {PersonId = 1, PersonName = "TONY"};
dr1[1] = new Student { StudentId = 1, StudentName = "TONY" };
_simpleDataTable.Rows.Add(dr1);

var dr2 = _simpleDataTable.NewRow();
dr2[0] = new Person { PersonId = 2, PersonName = "MAL" };
dr2[1] = new Student { StudentId = 2, StudentName = "MAL" };
_simpleDataTable.Rows.Add(dr2);

请告诉我如何绑定上述类型的DataTable。

【问题讨论】:

  • @SLaks _simpleDataTableDataGrid 以显示数据

标签: c# wpf data-binding datatable


【解决方案1】:

这是一个基于问题要求和these answers

的工作示例解决方案

主窗口

XAML

<Window x:Class="HowBindDataTableToDataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!-- you need foreach class one DataTemplate-->
        <DataTemplate x:Key="PersonDataTemplate" DataType="Person">
            <StackPanel>
                <TextBlock Background="LightBlue" Text="{Binding PersonId}"/>
                <TextBlock Background="AliceBlue" Text="{Binding PersonName}"/>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="StudentDataTemplate" DataType="Student">
            <StackPanel>
                <TextBlock Background="Orange" Text="{Binding StudentId}"/>
                <TextBlock Background="Yellow" Text="{Binding StudentName}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <DataGrid Name="simpleDataGrid" AutoGeneratingColumn="simpleDataGrid_AutoGeneratingColumn" />
    </Grid>
</Window>

.CS

using System.Data;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;

namespace HowBindDataTableToDataGrid
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            simpleDataGrid.ItemsSource = LoadDataTable().AsDataView();
        }

        private void simpleDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.PropertyType == typeof(Person))
            {
                MyDataGridTemplateColumn col = new MyDataGridTemplateColumn();
                col.ColumnName = e.PropertyName;
                col.CellTemplate = (DataTemplate)FindResource("PersonDataTemplate");
                e.Column = col;
                e.Column.Header = e.PropertyName;
            }
            else if (e.PropertyType == typeof(Student))
            {
                MyDataGridTemplateColumn col = new MyDataGridTemplateColumn();
                col.ColumnName = e.PropertyName;
                col.CellTemplate = (DataTemplate)FindResource("StudentDataTemplate");
                e.Column = col;
                e.Column.Header = e.PropertyName;
            }
        }

        private DataTable LoadDataTable()
        {
            var _simpleDataTable = new DataTable();

            var person = new DataColumn("Person") { DataType = typeof(Person) };
            _simpleDataTable.Columns.Add(person);

            var student = new DataColumn("Student") { DataType = typeof(Student) };
            _simpleDataTable.Columns.Add(student);

            var dr1 = _simpleDataTable.NewRow();
            dr1[0] = new Person { PersonId = 1, PersonName = "TONY" };
            dr1[1] = new Student { StudentId = 1, StudentName = "TONY" };
            _simpleDataTable.Rows.Add(dr1);

            var dr2 = _simpleDataTable.NewRow();
            dr2[0] = new Person { PersonId = 2, PersonName = "MAL" };
            dr2[1] = new Student { StudentId = 2, StudentName = "MAL" };
            _simpleDataTable.Rows.Add(dr2);

            return _simpleDataTable;
        }
    }

    public class MyDataGridTemplateColumn : DataGridTemplateColumn
    {
        public string ColumnName { get; set; }

        protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            // The DataGridTemplateColumn uses ContentPresenter with your DataTemplate.
            ContentPresenter cp = (ContentPresenter)base.GenerateElement(cell, dataItem);
            // Reset the Binding to the specific column. The default binding is to the DataRowView.
            BindingOperations.SetBinding(cp, ContentPresenter.ContentProperty, new Binding(this.ColumnName));
            return cp;
        }
    }
}

Person.cs

namespace HowBindDataTableToDataGrid
{
    public class Person
    {
        private int personId;
        private string personName;

        public int PersonId
        {
            get { return personId; }
            set { personId = value; }
        }
        public string PersonName
        {
            get { return personName; }
            set { personName = value; }
        }
    }
}

Student.cs

namespace HowBindDataTableToDataGrid
{
    public class Student
    {
        private int personId;
        private string personName;

        public int StudentId 
        {
            get { return personId; }
            set { personId = value; }
        }
        public string StudentName 
        {
            get { return personName; }
            set { personName = value; }
        }
    }
}

【讨论】:

    【解决方案2】:

    非 WPF DataGrid 的解决方案:

    //Create DataTable
    
    DataTable dt = new DataTable();
    
    //Put some columns in it.
    
    dt.Columns.Add(new DataColumn("Item #", typeof(int)));
    
    dt.Columns.Add(new DataColumn("Contract Number", typeof(string)));
    
    dt.Columns.Add(new DataColumn("Customer Name", typeof(string)));
    
    // Create the record
    
    DataRow dr = dt.NewRow();
    
    dr["Item #"] = i;
    
    dr["Customer Name"] = xmn2[1].InnerText;  //value from textbox on screen
    
    dr["Contract Number"] = xmn4[1].InnerText; //value from textbox on screen
    
    dt.Rows.Add(dr);
    
    //Bind the GridView to the data in the data table for display.
    
    this.GridView1.Visible = true;
    
    GridView1.DataSource = dt;
    
    GridView1.DataBind();
    

    【讨论】:

    • 此解决方案适用于普通数据网格,不适用于 WPF 数据网格。
    • -1 此解决方案仅适用于简单数据类型。他需要一些带有 DataTemplate 的东西
    【解决方案3】:

    试试这个:

    DataTable _simpleDataTable = new ataTable();
    DataGridInstance.AutoGenerateColumns = true;
    DataGridInstance.ItemsSource = _simpleDataTable.DefaultView;
    

    【讨论】:

    • -1 此解决方案仅适用于简单数据类型。他需要DataTemplate
    【解决方案4】:
    DataGrid.ItemsSource = DataTable.AsDataView();
    

    或者换句话说,你可以做到

    yourDataGridInstance.AutoGenerateColumns = true;
    yourDataGridInstance.ItemsSource = _simpleDataTable.AsDataView();
    

    【讨论】:

    • -1 此解决方案仅适用于简单数据类型。他需要DataTemplate
    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2018-02-07
    • 2023-04-06
    • 2015-12-14
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多