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

本文关键字:加载 数据库 数据 datagridview sql 组合 | 更新日期: 2023-09-27 18:18:01

我有三个列ID, CUSTOMERNAMEADDRESS的SQL表

我想在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>

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

这个比较简单,你可以试一试。

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.");
    }
}