how we can bind values in combobox and insert into database when we create dynamic combobox in c#..please help me..

Hi

The following is an example of how you can create a dynamic ComboBox and bind some data to it, you will need to modify according to your database, this example uses an SQL Server database:

ComboBox myDynamicComboBox;

private void Form1_Load(object sender, EventArgs e)
{
    //Create the combo box and add it to the form
    myDynamicComboBox = new ComboBox();
    myDynamicComboBox.Location = new System.Drawing.Point(100, 100);

    this.Controls.Add(myDynamicComboBox);

    //Add an event handler to the combo box so that we can display some information when the selected index changes
    myDynamicComboBox.SelectedIndexChanged += myDynamicComboBox_SelectedIndexChanged;

    //Get data and bind to the combo box, change your connection string and query accordingly
    string connectionString = @"Server=DJJEAVONS-PC\SQLEXPRESS;Database=Test;Trusted_Connection=True;";
    string selectStatement = "SELECT ID, SomeTextColumn FROM Test_Table";

    using(SqlDataAdapter adapter = new SqlDataAdapter(selectStatement, connectionString))
    {
        DataTable table = new DataTable();
        adapter.Fill(table);

        //Bind the DataTable to the ComboBox
        myDynamicComboBox.DataSource = table;
        myDynamicComboBox.DisplayMember = "SomeTextColumn";
        myDynamicComboBox.ValueMember = "ID";
    }

}

void myDynamicComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    //Display the ID and SomeTextColumn values from the combo box
    MessageBox.Show(String.Format("{0}-{1}", myDynamicComboBox.SelectedValue.ToString(), myDynamicComboBox.Text));
}

In terms of inserting data back into the database, you have the values available to you regarding the selected item, as demonstrated in the SelectedIndexChanged event so it should be fairly straightforward to write data back to the database.

HTH

thank's a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.