0

我制作了一个基本程序来向数据集添加值并将其显示到 dataGridView:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DataTable table1 = new DataTable("People");
        table1.Columns.Add("id");
        table1.Columns.Add("Name");
        table1.Columns.Add("Age");
        table1.Rows.Add(1, "Jack", 18);
        table1.Rows.Add(2, "Tim", 18);

        DataSet set = new DataSet("SetPeople");
        set.Tables.Add(table1);

        dataGridView1.DataSource = set;
        dataGridView1.Update();
    }
}

当我尝试它时,似乎什么都没有发生。dataGridView 保持空白。知道我哪里出错了吗?

4

3 回答 3

3

尝试这个

   dataGridView1.DataSource = table1;

您不需要 Ds 来仅在 Gridview 中显示数据表

于 2012-09-10T15:28:29.320 回答
2

Massimiliano Peluso is correct. The GridView will reference a"Table", but more specifically, when using ADO.NET in a Disconnected fashion you will be filling the GridView with DataColumn objects that are part of a DataTable object. You will also want to bind your dataTable to the GridView.

A bit of Detail: ADO.Net's DataSet construct allows you to represent your database in a "table" like manner and allow those tables to share references. All of this comes at the cost of additional memory overhead, but if this is not going to be a highly scalable applicaiton and you want to give the users the ability to edit rows without having to go to the database every time, DataSet is a good option.

If you are not using the featuers of DataSet (e.g. table relationships) you can save yourself a little overhead by just using DataTable objects and populating them.

To answer your questions:

A GridView expects to recieve a DataTable as a data source. That table can contain several columns (which will fill the columns of the grid). You can write the following code to specifically access your data table:

dataGridView1.DataSource = set.Tables["table1"]; // or by index if you prefer as there are several overloads.

Additionally, I would bind the data by adding the following line of code after the one perscribed above:

dataGridView1.DataBind();

The fact you are missing your DataBind() method call is part of your issue.

There is a very good example at C sharp corner site: Example

于 2012-09-10T15:59:05.957 回答
0

你也可以这样做:

dataGridView1.DataSource = set;
dataGridView1.DataMember = set.Tables["People"].TableName;
dataGridView1.Update();
于 2015-09-15T13:12:50.107 回答