English 中文(简体)
从数据集填充数据GridView
原标题:Filling DataGridView from Dataset

我有一个 < code> DataSet 和一个 < code> DataGridView 。 如果我单击第一个按钮, 我想从第一个表格显示数据, 如果我单击第二个表格显示数据 。

我尝试了以下

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

但我看到的是空的 DataGridView (不含列名)。

问题回答

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

您是否在指定数据源后拨打过数据文件夹?

dataGridView1.DataBind()




相关问题
Bring window to foreground after Mutex fails

I was wondering if someone can tell me what would be the best way to bring my application to the foreground if a mutex was not able to be created for a new instance. E.g.: Application X is running ...

How to start WinForm app minimized to tray?

I ve successfully created an app that minimizes to the tray using a NotifyIcon. When the form is manually closed it is successfully hidden from the desktop, taskbar, and alt-tab. The problem occurs ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

Handle DataTable.DataRow cell change event

I have a DataTable that has several DataColumns and DataRow. Now i would like to handle an event when cell of this DataRow is changed. How to do this in c#?

Apparent Memory Leak in DataGridView

How do you force a DataGridView to release its reference to a bound DataSet? We have a rather large dataset being displayed in a DataGridView and noticed that resources were not being freed after the ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

WPF-XAML window in Winforms Application

I have a Winforms application coded in VS C# 2008 and want to insert a WPF window into the window pane of Winforms application. Could you explain me how this is done.

热门标签