Matt Pruent
Matt Pruent

Reputation: 119

How would I change an item in a combobox?

I want to let users manipulate the data that I have put into a combo box. The thing is I can't figure out a way to apply the change to the data inside the combo box. Any clues as to how to achieve this?

To add some context all the data in my combo box are strings which have the format "SomeName|#" . The number at the end is modified by the user to whatever he/she desires.

Upvotes: 2

Views: 10312

Answers (1)

msivri
msivri

Reputation: 322

Are you trying to change the text in the selected combobox item?

   comboBox.Items[comboBox.SelectedIndex] = "SomeName|#";

As for changing data, if the above is not what you want, than try this:

// Get the selected the data from the combobox 
MyData data = comboBox.Items[comboBox.SelectedIndex] as MyData;
// Perform your operations
data.myData = "NewData";
// Add the modified data back
comboBox.Items[comboBox.SelectedIndex] = data;

If bound to a list:

  // When adding new Data
    MyData newData = new MyData("Data1");
    comboBox1.Items.Add(newData);
    myDataList.Add(newData);

    // When modifying selected data
    MyData data = comboBox1.Items[comboBox1.SelectedIndex] as MyData;
    data.myData = "NewData";
    comboBox1.Items[comboBox1.SelectedIndex] = myDataList[comboBox1.SelectedIndex] = data;

In case you are wondering what MyData is:

public class MyData
{
    public string myData;

    public MyData(string p)
    {
        myData = p;
    }

    public override string ToString()
    {
        return myData;
    }
}

EDIT Ok, if you are binding to a data source you need to unbind it first, lets assume the data source is myDataList:

        // Get the selected data
        MyData data = myDataList[comboBox.SelectedIndex] as MyData;
        // Unbind
        comboBox.DataSource = null;

        // When adding new Data
        MyData newData = new MyData("NewData" + myDataList.Count());
        myDataList.Add(newData);

        // When modifying selected data
        data.myData = "ModifiedData";

        // Rebind
        comboBox.DataSource = myDataList;

Upvotes: 5

Related Questions