使用组合框值从sql数据库将数据加载到datagridview

时间:2016-11-15 23:41:47

标签: c#

我的SQL表包含三列IDCUSTOMERNAMEADDRESS

我想在combobox1中显示所有客户ID的列表,当我选择任何一个ID时,应该在datagridview1中显示的客户名称和地址属于该ID。

请教我代码,因为我正在学习C#编程

以下是我的app.config供您参考

<connectionStrings>
    <add name="dbx" 
         connectionString="Data Source=USER\SQLEXPRESS;Initial Catalog=dbInventory;Integrated Security=True"  
         providerName="System.Data.SqlClient" />
</connectionStrings>

1 个答案:

答案 0 :(得分:1)

这是一个简单的尝试。

private void BindData(string selectCommand)
{
    try
    {
        string selectCommand = "SELECT * FROM tblCustomers";
        String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;;

        // Create a new data adapter based on the specified query.
        var dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

        // Create a command builder to generate SQL update, insert, and
        // delete commands based on selectCommand. These are used to
        // update the database.
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

        // Populate a new data table and bind it to the BindingSource.
        DataTable table = new DataTable();
        dataAdapter.Fill(table);
      dataGridView1.DataSource = table;
    }
    catch (SqlException)
    {
        MessageBox.Show("To run this example, replace the value of the " +
            "connectionString variable with a connection string that is " +
            "valid for your system.");
    }
}