c#- listbox how to get listbox values by index - c#

I wantto know how to take list box values by index ? in my list box for first index i have content ="one"
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
string[] n = new string[1];
n[0] = listBox1.Items[0].ToString();
txtbox1.Text = n[0];
}
Using above code when I get the first list box value it returns this:
System.Windows.Controls.ListBoxItem: one
How can get only the content of the listItem(index)
Can anyone please help me?

I must admit that i'm not familiar with WPF controls but MSDN shows it:
ListBoxItem lbi = listBox1.Items[0] as ListBoxItem; // cast object to ListBoxItem
txtbox1.Text = lbi.Content.ToString();
So you have to use the Content property of the ListBoxItem. You are using ToString which just returns the fully qualified name of the type if ToString was not overridden meaningfully.
If the ListBox is empty, you get an exception if you try to access the first item via index, the you have to check it first:
if(listBox1.HasItems) // you can also use listBox1.Items.Count > 0
{
ListBoxItem lbi = listBox1.Items[0];
// ...
}

Simply use
n[0] = listBox1.Items[0].Content.ToString();
instead of
n[0] = listBox1.Items[0].ToString();
Because .ToString() on the ListBox just returns the control as string. You need to call Text.ToString() to when you want to get the text you can see as string.

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.

How to get listbox selected item value

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();

combobox returning null value in c#

Here I created a for loop to list a range of numbers from 1 to 30 in the comboBox, but when I try to display the selected item from the combobox into a MessageBox it returns a null value. How can I get it to return the number selected from the comboBox? Here is my code:
string selectedNumber;
public Form1()
{
InitializeComponent();
for (int i = 1; i <= 30; i++)
{
string[] numbers= { i.ToString() };
comboBox1.Items.AddRange(numbers);
}
selectedNumber = comboBox1.SelectedText;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(selectedNumber);
}
}
Reason is clear that you have no text selected
You've to select any item in combobox first. To do so try any of the following
Set SelectedIndex to some valid index
Set SelectedItem to a valid item in combobox through code
Select an item in combobox by clicking it
Then use following code
MessageBox.Show(comboBox1.SelectedText); or
if(comboBox1.SelectedItem != null)//check for null since `SelectedItem` can be null when nothing selected
MessageBox.Show(comboBox1.SelectedItem.ToString());
Note: As #tim pointed in comments SelectedText approach won't work when DropDownStyle set to DropDownList. In that case you've to use SelectedItem approach
Here, with null check:
private void button1_Click(object sender, EventArgs e)
{
var selectedItem = comboBox1.SelectedItem ?? "";
MessageBox.Show(selectedItem.ToString());
}
As several have pointed out, there is nothing selected in the ComboBox when you assign SelectedText to selectedNumber. I would try two things:
First, don't call AddRange every time through the loop - build the array in the loop and then once the loop exits you can use AddRange. I would also use a List<string>:
List<string> numbers = new List<string>();
for (int i = 1; i <= 30; i++)
{
numbers.Add(i.ToString());
}
comboBox1.AddRange(numbers);
Secondly, in your button click event, show the selected text:
MessageBox.Show(comboBox1.SelectedText);
If comBox1's DropDownStyle is set to DropDownList, SelectedText will give an empty string. In that case, something like this might help:
MessageBox.Show(comboBox1.SelectedItem.ToString());
In reality, you'd probably want to handle the corresponding selection changed event for ComboBox as you'd probably want to do something with it in your program, but it looks like you're just trying some things out right now.
Edited To Add
Note that as Sriram said, SelectedItem can be null, so you'll want to check for that condition with either Sriram's or Przemyslaw's code if you're using SelectedItem instead of SelectedText.
Or, you can try this
for (int x = 0; x <= 30; x++)
comboBox1.Items.Add(x.ToString());
I find it a lot simpler

How to Get id key from List View - C# Windows application

I am listing set of table items(only names) in List View. I enabled checkbox property of ListView. I displayed all items as Large icons. I want to attach a key(id) for that items for further processing on that items.. If any idea , please reply
Use the ListViewItem.Name property. Poorly named, it is actually the key. The one you can pass to ListView.Items.IndexOfKey() or ListView.Items["key"].
Description
You should use the Tag property for things like that.
Gets or sets the object that contains data about the control.
You can set your id or any other object to the ListItem you want.
Sample
Add the Item
ListViewItem myItem = new ListViewItem();
myItem.Tag = 1; // or any other object
listView1.Items.Add(myItem);
Use the index
private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
ListViewItem myItem = e.Item;
int index = (int) myItem.Tag; // cast to your object type, int in this case
// use the index
}
More Information
MSDN - Control.Tag Property

Categories