Skip to main content
 首页 » 编程设计

c#之从数据集中填充 DataGridView

2024年02月20日13over140

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

我尝试了以下方法

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

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

请您参考如下方法:

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

为您的按钮创建公共(public)事件,在 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"]; 
    }