Ashfaque Baig
Ashfaque Baig

Reputation: 53

Load Data in to datagridview from sql database using combobox value

I have SQL table with three columns ID, CUSTOMERNAME and ADDRESS.

I want to show list of all customers ID in combobox1 and when I will select any one ID then Customer name and address should show in datagridview1 belongs to that ID.

Please advice me code as I am learning programming in C#

Below is my app.config for your reference

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

Upvotes: 0

Views: 219

Answers (1)

Aruna
Aruna

Reputation: 12022

This is the simple one which you can give a try.

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

Upvotes: 1

Related Questions