0
votes

I am doing c# winform development.

I have a tabcontrol that consists several tabpages. Some of the tabpages are filled with usercontrol fully, some are just filled with combboxes/textboxes as such.

I set datasource for comboboxes and it loaded ok. But, when I pass the entire tabcontrol instance as a parameter to another form, in the new form, the combo box selections are cleared and set to first item selected.

Strangely enough, for comboboxes that was put in a usercontrol, the selections were not clear and shown correctly in the new form. Only those were put directly in tab page do not work.

Any suggestions or help will be appreciated.

2
are you looking for a solution so that your ComboBoxes behave as you want, or investigating the reason behind the way they are behaving now? - atiyar

2 Answers

1
votes

bro. Fine? About the combobox problem, i have the same. I solve by this way: don't use DataSource

Before (with problem):

comboBox.DisplayMember = "NmConta";
comboBox.ValueMember = "CodConta";
comboBox.DataSource = dataTable;            

After (nothing problem):

comboBox.DisplayMember = "Value";
comboBox.ValueMember = "Key";
foreach (DataRow row in dataTable.Rows)
{
    comboBox.Items.Add(new KeyValuePair<int, string>(Convert.ToInt32(row["CodConta"]), Convert.ToString(row["NmConta"])));
}
0
votes

After the implementation above, i need to write this methods for read and write comboBox.SelectedValue:

// Set ComboBox.SelectedValue
private void ComboBoxSelectedValue(ComboBox comboBox, object valueToSelect)
{
    for (int i = 0; i < comboBox.Items.Count; i++)
    {
        object item = comboBox.Items[i];
        object value = item.GetType().GetProperty("Key").GetValue(item, null);
        if (Convert.ToString(value) == Convert.ToString(valueToSelect))
        {
            comboBox.SelectedIndex = i;
            return;
        }
    }
    comboBox.SelectedIndex = -1;
}

// Get ComboBox.SelectedValue
private object ComboBoxSelectedValue(ComboBox comboBox)
{
    if (comboBox.SelectedIndex < 0) { return null; }
    object item = comboBox.Items[comboBox.SelectedIndex];
    return item.GetType().GetProperty("Key").GetValue(item, null);
}

// Get ComboBox.SelectedText
private object ComboBoxSelectedText(ComboBox comboBox)
{
    if (comboBox.SelectedIndex < 0) { return null; }
    object item = comboBox.Items[comboBox.SelectedIndex];
    return item.GetType().GetProperty("Value").GetValue(item, null);
}