简体   繁体   中英

C# Combobox item text change?

I'm making the combobox which contains list of added Home adresses from DB, I'm trying to implement the option to change the text of what the current adress is called in combobox. For examples its now adressID fetched from db, but I'd like to add a option to call it for example "Adress 1" instead of just adressID.. I've tried some options from before suggested examples from google, but I get this error: Items collection cannot be modified when the DataSource property is set. because im using datasource. Anyone have an idea on how could this be fixed?

This is my code:

        private void getAdr()
    {
        string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();

        SqlCommand getAdr = new SqlCommand("SELECT adressID, userID, adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);
        SqlParameter parUserID = new SqlParameter("@userID", Login.id);
        getAdr.Parameters.Add(parUserID);
        getAdr.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(getAdr);
        DataTable dt = new DataTable();
        da.Fill(dt);




        comboBox1.DataSource = dt;
        comboBox1.DisplayMember = "adressID";
        comboBox1.ValueMember = "adressID";


        textBox5.DataBindings.Add("Text", dt, "adress");
        textBox6.DataBindings.Add("Text", dt, "floor");
        textBox7.DataBindings.Add("Text", dt, "city");
        textBox8.DataBindings.Add("Text", dt, "state");
        textBox9.DataBindings.Add("Text", dt, "country");
        textBox10.DataBindings.Add("Text", dt, "zipcode");


        comboBox1.Items[comboBox1.SelectedIndex] = "Adress 1";

    }

I think you should implement the TextChanged event of the combobox. When the user changes the addressID you should update your DB by using SqlCommand and then reload the datasource to refresh the combobox items.

When you set datasource property what you must change is that property and automatically your changes are visible in the combo.

For doing that i recommend you to use BindingSource object like this:

 BindingSource Adresses = new BindingSource();
 Adresses.DataSource = dt;

 comboBox1.DataSource = Adresses;
 comboBox1.DisplayMember = "adressID";
 comboBox1.ValueMember = "adressID";

When you change some data in dt object you should call:

Adresses.ResetBindings(true);

To updtate combo's data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM