Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a value in combobox that's populated from a DataTable

I have a combobox being populated by a DataTable as shown below. I want to be able to set which item is shown. The value it is to be set to is a string that will be found in the "Id" column.

public DataTable list = new DataTable();
public ComboBox cbRates = new ComboBox();

//prepare rates combo data source
this.list.Columns.Add(new DataColumn("Display", typeof(string)));
this.list.Columns.Add(new DataColumn("Id", typeof(string)));

//populate the rates combo
int counter = 0;

foreach (string item in dropdownItems)
{
    this.list.Rows.Add(list.NewRow());
    if (counter == 0)
    {
    this.list.Rows[counter][0] = "Select Rate..";
    this.list.Rows[counter][1] = "";
}
else
{
string[] itemSplit = item.Split('`');
if (itemSplit.Length == 2)
{
    this.list.Rows[counter]["Display"] = itemSplit[0];
    this.list.Rows[counter]["Id"] = itemSplit[1];
}
else
{
    this.list.Rows[counter]["Display"] = item;
    this.list.Rows[counter]["Id"] = item;
}
}
counter++;
}
this.cbRates.DataSource = list;
this.cbRates.DisplayMember = "Display";
this.cbRates.ValueMember = "Id";

//now.. how to set the selected value?

int rowCount = 0;
foreach (DataRow cbrow in this.list.Rows)
{
    if (DB.GetString(cbrow["Id"]) == answerSplit[1])
    {
        //attempting to set the SelectedIndex throws an exception
        //on another combobox populated NOT from a DataTable - this does work fine.
        this.cbRates.SelectedIndex = rowCount;
    }
    rowCount++;
}

//this doesn't seem to do anything.
foreach (DataRow dr in this.list.Rows)
{
    if ((string)dr["Id"] == answerSplit[1]) this.cbRates.SelectedItem = dr;
}

//nor this
foreach(DataRow dr in this.cbRates.Items)
{
   try
   {
     if ((string)dr["Id"] == answerSplit[1]) this.cbRates.SelectedItem = dr;
   }
    catch
    {
      MessageBox.Show("Ooops");
    }
}

Without FindExactString, FindString, FindByValue being not present in compact framework I am running out of things to try.

If attempt to use

this.cbRates.SelectedIndex = 2;

I get the following error;

System.Exception: Exception
at Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)
at System.Windows.Forms.ComboBox.set_SelectedIndex(Int32 value)

However, if I put the relevant code into it's own form for testing purposes I can set the selectedIndex without error.

I think these issues are linked.

like image 786
Mark Avatar asked Nov 16 '25 05:11

Mark


1 Answers

Are you aware that you can use the datatable directly as datasource?

        cbo.DataSource = table;
        cbo.DisplayMember = "Display";
        cbo.ValueMember = "Id";
like image 164
Morten Avatar answered Nov 18 '25 20:11

Morten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!