C# 如何在 Windows 应用程序中将数据集绑定到 DataGridView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11099619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:28:39  来源:igfitidea点击:

How to bind Dataset to DataGridView in windows application

c#

提问by sonal

I have created Windows Application. In this, I have multiple tables in dataset, now I want to bind that to a single DataGridView. Can anybody help me?

我已经创建了 Windows 应用程序。在此,我在数据集中有多个表,现在我想将其绑定到单个 DataGridView。有谁能够帮助我?

采纳答案by Damith

following will show one table of dataset

以下将显示一张数据集表

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show

if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.

如果要显示多个表,则需要从所有表中创建一个数据表或自定义对象集合。

if two tables with same table schema

如果两个表具有相同的表架构

dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]

DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable

sample code to mode all tables

模式所有表的示例代码

DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
     dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;

回答by Badhon Jain

you can set the dataset to grid as follows:

您可以将数据集设置为网格,如下所示:

//assuming your dataset object is ds

//假设你的数据集对象是ds

datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();

tablename is the name of the table, which you want to show on the grid.

tablename 是要在网格上显示的表的名称。

I hope, it helps.

我希望,它有帮助。

B.R.

BR

回答by Sandeep Tawaniya

use like this :-

像这样使用:-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

我希望它有帮助!!