How to get the selected value from combo box in wpf? - c#

I am trying to get the DepartmentId after selecting the item in combo box and then assign it to the nameTextBox.Text. But when I run the program it gives Null Reference Exception.
var deptList = dr.ReadAllDepartment();
departmentCombobox.DisplayMemberPath = "DepartmentName";
departmentCombobox.SelectedValuePath = "DepartmentId";
departmentCombobox.ItemsSource = deptList;
nameTextBox.Text = departmentCombobox.SelectedValue.ToString();

SelectedValue is null because there is no selected value. The user didn't select a value in the brief moment between when you set the ItemSource and when you tried to access SelectedValue.

At some point departmentCombobox.SelectedValue is null and the ToString() is being called on null.
You can use the ? operator;
you can also select the first item on the ComboBox before trying to access it:
var deptList = dr.ReadAllDepartment();
departmentCombobox.DisplayMemberPath = "DepartmentName";
departmentCombobox.SelectedValuePath = "DepartmentId";
departmentCombobox.ItemsSource = deptList;
departmentCombobox.SelectedIndex = 0;
nameTextBox.Text = departmentCombobox.SelectedValue?.ToString();

Related

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
If you want to know which items are selected, you have two options:
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.
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.

how to set the default value to the drop down list in C#?

DataSet dsCurrency = new DataSet();
dsCurrency = ParamCurrency.SelectCurrencys();
ddCurrencyField.DataSource = dsCurrency;
ddCurrencyField.DataTextField = "CurrencyName";
ddCurrencyField.DataValueField ="CurrencyCode";
ddCurrencyField.DataBind();
How to select a default value to the dropdownlist control using C#?
If you know the value will exist:
ddCurrencyField.FindItemByText("YourDefaultText").Selected = true;
else
ListItem selectedListItem = ddCurrencyField.Items.FindItemByText("YourDefaultText");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
};
You can also find item by value :
ListItem selectedListItem = ddCurrencyField.Items.FindByValue("YourDefaultValue");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
};
I assume in your datasource object (dsCurrency) is not parsing the default value for the dropdown.
So first you will have to add the default item. After binding the datasource do the following.
ddCurrencyField.Items.Insert(0, new ListItem("-- Select --",0));
With the above code you will have a default/first item selected as "--Select--". If it does not select the first item then simply set the SelectedIndex to 0.
There are 2 ways to set the default item after populating a dropdown.
you can use the "SelectedValue" property
you can use the "SelectedIndex" property
Most of the code samples are given in the previous answers. But I prefer to use the "FindByValue" method.
ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf(ddCurrencyField.Items.FindByValue(myValue));
If you want to write a safe code please use the second option.
If this dropdown list is a combobox, use this:
ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf("Wanted Value");

comboBox select for first value

I have simple comboBox with:
cb_listaUczniow.ValueMember = "Key";
cb_listaUczniow.DisplayMember = "Value";
And I have constructor for this Form (classID is not important yet):
MyForm(int classID, string selectedName)
{
cb_listaUczniow.ValueMember = "Key";
cb_listaUczniow.DisplayMember = "Value";
comboBox.DataSource = new BindingSource(makeList(classID), null);
}
makeList return Dictionary
and How i can select in comboBox item with "Value" (displayMember) where names selectedName?
for example (pseudo-Code):
MyForm(3, "Gall Anonim") -> comboBox.Item.Selected = comboBox.Item.where("Value" == "Gall Anonim");
How i can set it?
If I understand this correctly, you can simply set ComboBox's SelectedValue property to the corresponding value :
comboBox.SelectedValue = 3;
That will make "Gall Anonim" the selected item of the ComboBox.

How to set Selected item of ComboBox in C# Windows Forms?

I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.
For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.
Not working code:
for (int i = 0; i < cmbVendor.Items.Count; i++)
if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
{
cmbVendor.SelectedIndex = i;
break;
}
You can get your item index by the .Items.IndexOf() method. Try this:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
You don't need to iterate.
You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.
The following is working for me perfectly. Pass any value or Text which is available in the combobox.
comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);
You have it in your if:
cmbVendor.SelectedItem = cmbVendor.Items[i];
At last I found it out. It's:
cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
If you have set ValueMember property for the ComboBox control, you can simply assingn the Value to the ComboBox control's SelectedValue property. You don't have to find the index explicitly.
Here's an example:
public class Vendor{
public int VendorId {get; set;}
public string VendorName {get; set;}
}
// Inside your function
var comboboxData = new List<Vendor>(){
new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
}
cmbVendor.DataSource = comboboxData;
cmbVendor.DisplayMember = "VendorName";
cmbVendor.ValueMember = "ValueId";
// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
cmbVendor.SelectedValue = 2;
Assuming gridView1.GetFocusedRowCellValue("vVendor") really works as expected, the following code should fix the problem.
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
{
cmbVendor.SelectedItem = item;
break;
}
}
The original code had multiple calls to gridView1.GetFocusedRowCellValue("vVendor"), whereas you only need one.
The suggested "comboBox1.Items.IndexOf(" assumes too much about the content of cmbVendor.Items.
I had a similar problem and worked it out partially with the help of the other answers here. First, my particular problem was that
combobox1.SelectedItem = myItem;
was not working as expected. The root cause was that myItem was an object from a group which was effectively the same list as the items in the combobox, but it was actually a copy of those items. So myItem was identical to a valid entry, but itself was not a valid object from the combobox1 container.
The solution was to use SelectedIndex instead of SelectedItem, like this:
combobox1.SelectedIndex = get_combobox_index(myItem);
where
private int get_combobox_index(ItemClass myItem)
{
int i = 0;
var lst = combobox1.Items.Cast<ItemClass >();
foreach (var s in lst)
{
if (s.Id == myItem.Id)
return i;
i++;
}
return 0;
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")
Try this this will work fine in C# Windows application
this works for me.....
string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;

How to get value from datagridview combobox?

How to get value from datagridview combobox after selected value is changed?
You can use:
var value = DataGridView.Rows[0].Cells[0].Value
NOTE: You would supply the correct row and cell number.
Or you can do something like this if it is bound to an object like ListItem
string value = DataGridView.Rows[RowIndex].Cells[ColumnIndex].Value.ToString();
if DataGridView.Rows[RowIndex].Cells[ColumnIndex] is DataGridViewComboBoxCell && !string.IsNullOrEmpty(value))
{
List<ListItem> items = ((DataGridViewComboBoxCellDataGridView.Rows[RowIndex].Cells[e.ColumnIndex]).Items.Cast<ListItem>().ToList();
ListItem item = items.Find(i => i.Value.Equals(value));
}
Do not pass to give column name
string SelectedText = Convert.ToString((Pass_dataGridView.Rows[0].Cells["Partner"] as DataGridViewComboBoxCell).FormattedValue.ToString());

Categories