Пеньо Русев
Пеньо Русев

Reputation: 11

Filling DataGridView from Dataset

I have a DataSet and a DataGridView. If I click the first button I want to show data from first table, and If I click the second I want to show data from the second table.

I tried the following

if(b==1)
{
    dataGridView1.DataSource = ds.Table1;
}
else if(b==1)
{
    dataGridView1.DataSource = ds.Table2;
}

But what I see is an empty DataGridView (without the column names).

Upvotes: 1

Views: 19463

Answers (2)

Niranjan Singh
Niranjan Singh

Reputation: 18280

DataSet add tables in the Tables collection and you can access these tables from this by their index or table name.

Create common event for your buttons, create as follow on Form_Load:

btn1.Click += new EventHandler(Button_Click);
btn2.Click += new EventHandler(Button_Click);

and then event method as:

void Button_Click(object sender, EventArgs e)
        {
            if ((sender as Button) == btn1)
            {
                dataGridView1.DataSource = ds.Tables[0];
            }
            else if ((sender as Button) == btn2)
            {
                dataGridView1.DataSource = ds.Tables[1];
            }
        }

////

if(b==1)
{
dataGridView1.DataSource = ds.Tables[0];
}
else if(b==2)
{
dataGridView1.DataSource = ds.Tables[1];
}

e.g.

DataTable dt = new DataTable("Table1");
DataTable dt2 = new DataTable("Table2");

DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.Tables.Add(dt2);

//Now you can access these as:

if(b==1)
    {
    dataGridView1.DataSource = ds.Tables["Table1"];
    }
    else if(b==2)
    {
    dataGridView1.DataSource = ds.Tables["Table2"];
    }

Upvotes: 4

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

Have you called databind after assigning the datasource ?

dataGridView1.DataBind()

Upvotes: 0

Related Questions