C# 如何在组合框中显示所有数据集

C# 如何在组合框中显示所有数据集,c#,sql-server,visual-studio,listview,combobox,C#,Sql Server,Visual Studio,Listview,Combobox,如何用项目中的所有数据集填充ComboBox 我的代码 foreach (DataTable table in DataSet.Tables) { foreach (DataRow row in table.Rows) { foreach (DataColumn column in table.Columns) {

如何用项目中的所有数据集填充ComboBox

我的代码

 foreach (DataTable table in DataSet.Tables)
            {
                foreach (DataRow row in table.Rows)
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        object item = row[column];

                    }
                }
                comboBox1.Items.Add(table.TableName);
            }

您只需要用表名填充组合框

foreach (DataTable table in DataSet.Tables)
        {
            comboBox1.Items.Add(table.TableName);
        }
然后,您需要对组合框的Select事件进行编码,该事件可能如下所示

private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    //fill listview with items that belong to the combobox.SelectedItem
    //since you filled the combobox with table.TableName, the name will be in .SelectedItem
}
别忘了

this.comboBox1.SelectedIndexChanged += new System.EventHandler(comboBox1_SelectedIndexChanged);

修改您的查询,使sql命令的结果中包含所有数据,如下所示

        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        SqlDataAdapter adapter = new SqlDataAdapter();
        DataSet ds = new DataSet();
        int i = 0;
        string sql = null;
        connetionString = "Data Source=.;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
        sql = "select au_id,au_lname from authors";
        connection = new SqlConnection(connetionString);
        try
        {
            connection.Open();
            command = new SqlCommand(sql, connection);
            adapter.SelectCommand = command;
            adapter.Fill(ds);
            adapter.Dispose();
            command.Dispose();
            connection.Close();
            comboBox1.DataSource = ds.Tables[0];
            comboBox1.ValueMember = "au_id";
            comboBox1.DisplayMember = "au_lname";
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! ");
        }

此代码用表名填充组合框。剩下的你都试了些什么?有什么问题吗?什么东西没有按预期工作?您应该查看combobox的事件,并使用它来检测何时选择了一个表,以便您可以填充listview。我不想用tablename填充combobox,我想在combobox中显示数据库名称无论您用什么填充它,它都将用于填充listview。如果table.TableName是一个数据库名称,那么您将用所述数据库内容填充listView。