2012-05-25 80 views
1

我有一个DataSet和一个DataGridView。如果我点击第一个按钮,我想显示第一个表中的数据,如果我点击第二个,我想显示第二个表中的数据。从数据集中填充DataGridView

我尝试以下

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

但我看到的是一个空DataGridView(没有列名)。

回答

3

DataSet在Tables集合中添加表,您可以通过它们的索引或表名访问这些表。

您的按钮创建常见的事件,创造尽可能遵循的Form_Load:

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

,然后活动的方法:

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]; 
} 

例如

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"]; 
    } 
0

您是否在分配数据源之后调用了数据绑定?

dataGridView1.DataBind() 
+0

...认为该选项仅适用于Web窗体而不是您的winFroms – whytheq