如何将 DataTable 绑定到 DataGrid

     2023-02-22     59

关键词:

【中文标题】如何将 DataTable 绑定到 DataGrid【英文标题】:How Bind DataTable to 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 以显示数据 【参考方案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

如何将 DataTable.Select() 的结果绑定到 ListBox 控件?

】如何将DataTable.Select()的结果绑定到ListBox控件?【英文标题】:HowdoIbindtheresultofDataTable.Select()toaListBoxcontrol?【发布时间】:2010-09-1200:09:08【问题描述】:我有以下代码:ListBox.DataSource=DataSet.Tables("table_name").Select("some_criteria=match")... 查看详情

如何将 DataTable 绑定到由 DatagridViewTextBoxColumn 和 DataGridViewComboBoxColumn 组成的 DataGridView?

】如何将DataTable绑定到由DatagridViewTextBoxColumn和DataGridViewComboBoxColumn组成的DataGridView?【英文标题】:HowtobindDataTabletoDataGridViewthatconsistsofaDatagridViewTextBoxColumnandaDataGridViewComboBoxColumn?【发布时间】:2014-01-2807:48:01 查看详情

如何将每行具有不同组合框项的 DataTable 绑定到 DataGridView?

】如何将每行具有不同组合框项的DataTable绑定到DataGridView?【英文标题】:HowtobindDataTablewithdifferentcomboboxitemseachrowtoDataGridView?【发布时间】:2021-11-1521:55:59【问题描述】:我创建了一个这样的通用数据表,没关系:BindingSourcebindi... 查看详情

如何将新的 DataRow 添加到 DataTable 中?

】如何将新的DataRow添加到DataTable中?【英文标题】:HowtoaddnewDataRowintoDataTable?【发布时间】:2012-09-2814:32:17【问题描述】:我有一个DataGridView绑定到一个DataTable(DataTable绑定到数据库)。我需要将DataRow添加到DataTable。我正在尝... 查看详情

将 DataGrid 绑定到两个 DataTable

】将DataGrid绑定到两个DataTable【英文标题】:BindingDataGridtotwoDataTable【发布时间】:2015-12-1408:31:56【问题描述】:我有两个DataTable,它们的结构、架构和约束完全相同,但行不同。我需要将这些表显示为DataGrid,并连接在一起,即... 查看详情

将行号列添加到绑定到 DataTable 的 DataGridView

】将行号列添加到绑定到DataTable的DataGridView【英文标题】:AddrownumbercolumntoDataGridViewboundtoDataTable【发布时间】:2020-03-1306:41:33【问题描述】:在ADO.NET中,我使用DataAdapter.Fill(..)调用来使用数据库中的值填充DataTable。然后我将DataTa... 查看详情

将 DataTable 绑定到已定义列的 Datagridview

】将DataTable绑定到已定义列的Datagridview【英文标题】:BindDataTabletoDatagridviewthatalreadyhavecolumndefined【发布时间】:2013-06-2014:53:25【问题描述】:我正在尝试将DateTable绑定到Datagridview已经有在VS中使用Designer设计的列。DataTable的来源... 查看详情

如何将 DataGridView 组合框添加到绑定的 DataGridView 数据源(以编程方式)

】如何将DataGridView组合框添加到绑定的DataGridView数据源(以编程方式)【英文标题】:HowToAddADataGridViewComboBoxCelltoaBoundDataGridViewDataSource(Programatically)【发布时间】:2014-03-0204:58:05【问题描述】:目标在使用DataView设置我的DataGridVie... 查看详情

C# 将 DataTable 绑定到现有 DataGridView 列定义

】C#将DataTable绑定到现有DataGridView列定义【英文标题】:C#BindDataTabletoExistingDataGridViewColumnDefinitions【发布时间】:2011-02-1304:09:09【问题描述】:我一直在与NullReferenceException作斗争,希望这里有人能够为我指明正确的方向。我正在... 查看详情

如何将数据源绑定到 datagridview 组合框和复选框

】如何将数据源绑定到datagridview组合框和复选框【英文标题】:Howtobinddatasourcetodatagridviewcomboboxandcheckbox【发布时间】:2014-09-0507:33:40【问题描述】:我有一个带有组合框和复选框的数据网格视图。当我尝试从数据表中的datagridvie... 查看详情

将 DataTable 绑定到 RDLC 和 ReportViewer

】将DataTable绑定到RDLC和ReportViewer【英文标题】:BindDataTabletoRDLCandReportViewer【发布时间】:2014-03-0723:49:06【问题描述】:我已经阅读了所有关于此的SO问题和在线文章,但我在几个不同的情况下感到困惑。在我的项目中,我尝试... 查看详情

使用 TemplateColumns 将 WPF DataGrid 绑定到 DataTable

】使用TemplateColumns将WPFDataGrid绑定到DataTable【英文标题】:BindingWPFDataGridtoDataTableusingTemplateColumns【发布时间】:2011-02-1006:29:42【问题描述】:我已经尝试了所有方法,但一无所获,所以我希望有人能给我带来欢呼的时刻。我根本... 查看详情

如何将锯齿状数组绑定到 DataGridView?

...定到数据网格视图?或者将其转换为数据View或BindingList或DataTable,然后绑定到datagridview?编辑:Object[,]是完 查看详情

vb.net如何将两个datatable合并

我现在有两个datatable一个叫bill一个叫两个表中pRunID字段关联我想要除了这个字段的其他字段,生成一个新的datatable显示到表格控件中参考技术A自己新建一个table循环两个表数据取自己需要的放在自己新建的table。主要对vb不熟应... 查看详情

如何将datagridview转换为datatable?

DataGridView是转换不了DataTable的,因为DataGridView是控件,DataTable是数据结构,但是DataGridView的数据集是有可能的,前提是DataGridView绑定数据集的时候绑定的就是DataTable类型的数据集.DataTabledt=DataGridView.DataSourseasDataTable;参考技术As529586的正... 查看详情

如何防止 ComboBox 中的 NewItemPlaceholder 行绑定到与 WPF 中的 DataGrid 相同的 DataTable

...ComboBox中的NewItemPlaceholder行绑定到与WPF中的DataGrid相同的DataTable【英文标题】:HowtopreventNewItemPlaceholderrowinaComboBoxboundtothesameDataTableasaDataGridinWPF【发布时间】:2012-02-2304:56:14【问题描述】:我是一个使用页面的向导式应用程序,用... 查看详情

无法刷新绑定到 DataTable 的 DataGridView

】无法刷新绑定到DataTable的DataGridView【英文标题】:UnabletorefreshDataGridViewthatisboundtoaDataTable【发布时间】:2019-04-1122:58:50【问题描述】:我已经使用论坛上的其他答案尝试了所有方法。我只是希望我的数据网格视图在进行更改后... 查看详情

如何在已经绑定数据源的datagridview添加一行数据并保存到数据库??

网上有人说可以加一行这个就好((DataTable)dataGridView1.DataSource).Rows.Add("row");可是调试结果显示无法将类型为“System.Windows.Forms.BindingSource”的对象强制转换为类型“System.Data.DataTable”。求大神帮忙给出详细解答(本人完全菜... 查看详情