How to get listbox selected item value - c#

I am working with C# .NET 4.0
I am trying to get the value of a single selected item in a listbox.
This is how I populate the control:
this.files_lb.DataSource = DataTable object
In my designer, I have specified file_name as the DisplayMember and file_id as the DisplayValue
After selecting an item in the listbox, I tried the following to get the value:
this.files_lb.SelectedValue.ToString()
But all it returns is "System.Data.DataRowView".
At this link : Getting value of selected item in list box as string
someone suggested -
String SelectedItem = listBox1.SelectedItem.Value
However, 'Value' is not an option when I try this.
How can I get the ValueMember value from a single selected item in a listbox?

var text = (listBox1.SelectedItem as DataRowView)["columnName"].ToString();
Replace columnName with the name of the column you want to get data from, which will correspond with a column in your datasource.
Also watch out for nulls if there's no selected item.

It really should be this easy; I have the following in a click event for button to make sure I wasn't over simplifying it in my head:
private void button1_Click(object sender, EventArgs e)
{
string selected = listBox1.GetItemText(listBox1.SelectedValue);
MessageBox.Show(selected);
}
And the result:
Edit
It looks like your issue may be from not setting a property on the control:
Select the ListBox control
Click the little arrow to show the binding / items options
Select Use Data Bound Items
If I deselect that box, I get the exact same behavior you are describing.

var selectedValue = listBoxTopics.SelectedItem;
if (selectedValue != null)
{
MessageBox.Show(listBoxTopics.SelectedValue.ToString());
}

You may need to set the DataValueField of the listbox.
NewEmployeesLB.DataSource = newEmployeesPersons.DataList.Select(np => new
ListItem() { Text = np.LastName + ", " + np.FirstName, Value = np.PersonID.ToString() }).ToList();
NewEmployeesLB.DataTextField = "Text";
NewEmployeesLB.DataValueField = "Value";
NewEmployeesLB.DataBind();

Related

Get ListView Item Values of row tapped

Get ListView Item Values of row tapped. I am able to get the item tapped in code behind like so:
private async void Item_Tapped(object sender, ItemTappedEventArgs e)
{
ListView listView = (ListView)sender;
if (listView != null)
{
string pName = e.Item //.PNname; **<<-- This is returning my bound values (4 items) as PName, PNumber... and so on**
}
}
I try to type the .PName it is a sub value to the e.Item list but that is invalid. I really need to grab by name because it appears the return selected row item returns values in a random way? One time PName will be first then next it might be 2nd or 3rd?
Anyway what am I missing to grab the values I need?
I'm doing a lot more visual things here but wanted to keep this code very simple to what I am actually having an issue with getting the individual values in the row.
TIA!
Cheers!
Rick...
e.Item is an object (datatype), if I am not mistaken. You have to cast e.Item to the right data type first:
string pName = (e.Item as Person)?.PName;
(assuming that PName is a property of the class Person)
Try get the itemIndex clicked and get the element in the list or use the AutomationId.

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.

Add 2 or more field to value member of C# coding

I have table with 4 primary key fields. I load that in to drop down list in my WinForm application created by using C#.
On the TextChanged event of drop down list I have certain TextBox and I want to fill the information recived by the table for the certain field I selected by the drop down list.
So as I say the table having 4 fields. Can I get those all 4 fields into value member from the data set, or could you please tell me whether is that not possible?
Thank you.
Datatable dt=dba.getName();
cmb_name.ValueMember="id";
cmb_name.DisplayMember="name";
cmb_name.DataSource=dt;
this is normal format.. but i have more key fields.. so i need to add more key fields..
You can use DataSource property to bind your source data to the ComboBox (e.g. a List of Entities, or a DataTable, etc), and then set the DisplayMember property of the ComboBox to the (string) name of the field you want to display.
After the user has selected an Item, you can then cast the SelectedItem back to the original row data type (Entity, DataRow, etc - it will still be the same type as you put in), and then you can retrieve your 4 composite keys to the original item.
This way you avoid the SelectedValue problem entirely.
Edit:
Populate as follows:
cmb_name.DisplayMember = "name";
cmb_name.DataSource = dt;
// Ignore ValueMember and Selected Value entirely
When you want to retrieve the selected item
var selectedRow = (cmb_name.SelectedItem as DataRowView );
Now you can retrieve the 4 values of your PK, e.g. selectedRow["field1"], selectedRow["field2"], selectedRow["field3"] etc
If however you mean that you want to DISPLAY 4 columns to the user (i.e. nothing to do with your Table Key), then see here How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?
cmb_name.DisplayMember = "name";
cmb_name.DataSource = dt;
DataRowView selectedRow = (cmb_name.SelectedItem as DataRowView );
The result will be here:
MessageBox.Show(selectedRow.Row[0].ToString());
MessageBox.Show(selectedRow.Row[1].ToString());
MessageBox.Show(selectedRow.Row[2].ToString());
MessageBox.Show(selectedRow.Row[3].ToString());
.....
If you want to get some data from a ComboBox in to a List you can use something like this
List<string> ListOfComboData = new List<string>();
ListOfComboData = yourComboBox.Items.OfType<string>().ToList<string>();
I have no real idea if this is what you mean as the question is very poorly structured. I hope this helps...
Edit: To put the selected text in to some TextBox use
yourTextBox.Text = youComboBox.Text;
in the SelectedIndexChanged event of your ComboBox.
You could follow the approach here with the following class:
public class ComboBoxItem
{
public string Text { get; set; }
public object[] PrimaryKey { get; set; }
}
private void Test()
{
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.PrimaryKey = new object[] { primaryKey1, primaryKey2, primaryKey3, primaryKey4};
comboBox1.Items.Add(item);
comboBox1.SelectedIndex = 0;
MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}

What is the correct way to change selection of a DropDownList?

I am having a problem to change a selected item in a drop-down.
The way I use is (a property in the code behind which sets the new selection):
public char Candy
{
set
{
var newSelection = ddlCandy.Items.FindByValue(value.ToString());
ddlCandy.ClearSelection();
newSelection.Selected = true;
}
}
Is this a recommended and proper way?
recommended approach is to simply assign the SelectedValue property with the Value you have and the DropDownList control will find and select the proper item for you, if any.
Safe way is fist Find the given item from DropDownList and set it as SelectedValue
ListItem oListItem = DropDownList1.Items.FindByValue("yourValue");
if(oListItem != null)
{
DropDownList1.SelectedValue = oListItem.Value;
}
if you directly assign SelectedValue it may through an exception if it is not exist in the list like bellow.
'DropDownList' has a SelectedValue which is invalid because it does
not exist in the list of items.
I usually prefer to use SelectedValue:
DropDownList1.SelectedValue = "Foo";

Setting the selected value of a ListBoxView as a string (C#)

When a value is selected in a ListBoxView, How could the selection be stored as a string / variable, so I can then call another method that will use this string to perform an action?
If the Items in your listbox are all strings, you could use
System.Windows.Forms.ListBox lb= new ListBox();
lb.SelectedItem.ToString();
Otherwise, we will need to know the types of items you have added to the listbox.
If you using ListBox get selected item like this:
string item = listBox1.SelectedItem.ToString();
If you using ListView get selected item(s) depending on MultiSelect property:
Use this code if MultiSelect property = false
string itemName = listView.SelectedItems[0].Name;
Use this code if MultiSelect property = true
foreach (ListViewItem item in ltvMainMenu.SelectedItems)
{
string itemName = item.Name;
}

Categories