0

I created a table in dataset that is not in a database, I need to set data to this table and bind data to a combobox, how can I do this?

        DataRowView drv = statusBindingSource.AddNew() as DataRowView;
        drv.Row["Value"] = 1;
        drv.Row["Name"] = "Active";
        statusBindingSource.EndEdit();

        statusBindingSource.Add(drv);

I cannot add external objects to this list.

Roman Svitukha
  • 1,302
  • 1
  • 12
  • 22
MoHaMMaD
  • 19
  • 3
  • 1
    Are you aware a combobox can bind to anything that [implements IList or is an Array](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.combobox.datasource?view=netframework-4.8#property-value)? You don't need a DataSet/DataTable which is a much heavier object than a simple `List`. – Crowcoder May 26 '19 at 17:40
  • Yeah and do this to have that list saved https://stackoverflow.com/questions/2890271/how-to-save-a-liststring-on-settings-default. what i can think about is have dictionary of value and name stored in that list – OctaCode May 26 '19 at 18:00

1 Answers1

0

The new DataTable is created, filled with data and bound to the combo box. I did not include a DataSet or BindingSource.

    private void Form1_Load(object sender, EventArgs e)
    {
        CreateDataTable();
        cbo1.SelectedIndex = -1;
    }

    private void CreateDataTable()
    {
        //Create new DataTable
        DataTable dt = new DataTable();
        //Add colums with column name and datatype
        dt.Columns.Add("Value", Type.GetType("System.Int32"));
        dt.Columns.Add("Name", Type.GetType("System.String"));
        //Add data
        object[] data = { 1, "Active" };
        dt.Rows.Add(data);
        object[] data2 = { 2, "Passive" };
        dt.Rows.Add(data2);
        //Bind to combo box
        cbo1.DataSource = dt;
        cbo1.DisplayMember = "Name";
        cbo1.ValueMember = "Value";
    }

    private void Cbo1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        MessageBox.Show($"The display member is {((DataRowView)cbo1.SelectedItem)["Name"]}, The value member is {cbo1.SelectedValue}");
    }
Mary
  • 14,926
  • 3
  • 18
  • 27