Reputation: 585
I have made a basic program to add values to a dataSet and display it to a 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();
}
}
When I try it out nothing seems to happen. The dataGridView remains blank. Any idea where I am going wrong?
Upvotes: 0
Views: 19255
Reputation: 51
You could also do this:
dataGridView1.DataSource = set;
dataGridView1.DataMember = set.Tables["People"].TableName;
dataGridView1.Update();
Upvotes: 0
Reputation: 622
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
Upvotes: 2
Reputation: 26717
try this
dataGridView1.DataSource = table1;
you don't need a Ds for just showing a data table in a Gridview
Upvotes: 3