Pepe
Pepe

Reputation: 111

Getting current value of comboBox in SelectedValueChange event

I follow this instructions to create multi select combobox

So I have something like this:

 var empList = db.GetTableBySQL($"exec getTaskAssignableEmployeeList");


        checkBoxComboBox1.DataSource = new Utility.ListSelectionWrapper<DataRow>(empList.Rows, "Abbreviation");
        checkBoxComboBox1.DisplayMemberSingleItem = "Name";
        checkBoxComboBox1.DisplayMember = "NameConcatenated";
        checkBoxComboBox1.ValueMember = "Selected";
        checkBoxComboBox1.Tag = empList.Rows;

        checkBoxComboBox1.SelectedValueChanged += ComboEmployee_SelectedValueChanged;

As you can see I have ComboEmployee_SelectedValueChanged Event. So when I click into one checkbox I want to retrieve value of comboBox as:

private void ComboEmployee_SelectedValueChanged(object sender, EventArgs e)
        {

            var db = new SQLConnMgr();


            var employeeComboBox = sender as CheckBoxComboBox;
            var taskDataRow = employeeComboBox.Tag as DataRow;
            var taskTypeName = taskDataRow["Name"] as string;
         }

But I'm getting error because taskDataRow is always null, then when it try to execute var taskTypeName = taskDataRow["Name"] as string; I'm getting:

Object reference not set to an instance of an object.'

Why I cant retrieve taskDataRow fro\m comboBox? Regards

Upvotes: 0

Views: 582

Answers (1)

Niranjan Singh
Niranjan Singh

Reputation: 18290

If you want to know which items are selected, you have two options:

  1. Use the CheckBoxItems property on the ComboBox which is a list of items wrapping each item in the ComboBox.Items list. The CheckBoxComboBoxItem class is a standard CheckBox, and therefore the bool value you are looking for is contained in Checked.
  2. Or if you stored a reference to the ListSelectionWrapper<T>, you could use that to access the Selected property of the binded list.

-

if (ComboBox.CheckBoxItems[5].Checked)  
            DoSomething();

OR

if (StatusSelections.FindObjectWithItem(UpdatedStatus).Selected)
    DoSomething();

You are getting Null Reference exception because you have saved table.Rows in the tag of the combobox not the DataRow in the below line that why you are getting exception.

var taskDataRow = employeeComboBox.Tag as DataRow;

To resolve the issue, Iterate through CheckBoxItems and there you can get the selected item text. After that filter the data rows on the basis of selected item text or value.

Upvotes: 1

Related Questions