how to get DisplayMemeber value from listbox by valuemember c#? - c#

I have a listBox, something like this:
ID ClientName
Michael
Steve
Smith
Now, I know the ID of the client , how do i get the DisplayMember of it ?

Cast into DataRowView and convert select the client name column by index, which is 1.
String ClientName = (((DataRowView) listBox1.SelectedItem).Row[1]).ToString();

You could try this code. the example is written if the DataSource of the Listbox is DataTable, but if it is something else, try to see of what type is the object in Items property of the ListBox.
(Note that I don't like using break statement but this was the quickest way)
string str = string.Empty;
foreach (DataRowView drv in listBox1.Items)
{
int lvID = int.Parse(drv.Row[listBox1.ValueMember].ToString());
if (lvID == 5)
{
str = drv.Row[listBox1.DisplayMember].ToString();
break;
}
}

var t = from list in USStates where te.ShortName == textBox1.Text select te.LongName.ToString();
foreach(String st in t)
{
MessageBox.Show(st);
}
where USStates is Generic List and TextBox1.text contains the value of the id.Considering your listbox uses Generic list as DataSource.

There is a much easier solution. Especially if you are building the DataSource, populating it, then releasing the source. Use the Items list to create a DataRowView of the item currently selected. Then just pull the right index. 0 will give you the "value member" and 1 will give you the "display member".
DataRowView thisLine = cbTrackerFormList.Items[cbTrackerFormList.SelectedIndex] as DataRowView;

Related

How to retrieve selected values for selected items in a ListBox?

I'm populating a ListBox in a WinForms application, this way:
listBoxUsers.DataSource = ctx.Users.ToList();
listBoxUsers.DisplayMember = "Name";
listBoxUsers.ValueMember = "Id";
how to retrieve the selected Ids when I'm setting the SelectionMode to MultiSimple
I want to do a foreach loop on them, like this:
foreach(var itemId in listBoxUsers.SelectedValues)//unfortunately not exist
{
int id = int.Parse(itemId);
// . . .
}
Since you know the type of items, you can use such code:
var selectedValues = listBox1.SelectedItems.Cast<User>().Select(x=>x.Id).ToList();
Side Note: The ListBox control lacks a GetItemValue method. A method which should work like GetItemText, but for getting values. In the linked post I shared an extension method to get the value from an item. Using that extension method you can get selected values independent from type of items:
var selectedValues = listBox1.SelectedItems.Cast<object>()
.Select(x => listBox1.GetItemValue(x)).ToList();
If for some reason you are interested to have a text representation for selected values:
var txt = string.Join(",", selectedValues);
Have you tried with the SelectedItems property?
foreach (var item in listBoxUsers.SelectedItems)
{
}
try this:
foreach (DataRowView item in listBoxUsers.SelectedItems)
{
int id=int.parse(item[0].ToString());
}

Store elements from a ListView into a List

Since I haven't found anything that helped, I ask my question here:
I have a ListView where I select a whole row by click. Now I want to store these selected items into a List but don't know how this should work exactly.
List<String> itemSelected = new List<String>();
foreach (var selectedRow in listView1.SelectedItems)
{
itemSelected.Add(selectedRow);
}
That doesn't work because I need an index (selectedRow[?]) or something like that. How can I store the values of the first column when clicked the row?
EDIT: The problem is that the ListViewItems have the type "object"
The ListView gets populated this way:
using (SqlConnection connection = new SqlConnection(connectionQuery))
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
col1 = row.Cells[col1.Text].Value.ToString();
col2 = row.Cells[col2.Text].Value.ToString();
col1Cells.Add(col1);
col2Cells.Add(col2);
}
}
You can do something like:
ListViewItem listViewItem = this.listView1.SelectedItems.Cast<ListViewItem>().FirstOrDefault();
if (listViewItem != null)
{
string firstColumn = listViewItem.Text;
string secondColumn = listViewItem.SubItems[0].Text;
// and so on with the SubItems
}
If you have more selected items and only need the values of the first columns you can use:
List<string> values = listView1.SelectedItems.Cast<ListViewItem>().Select(listViewItem => listViewItem.Text).ToList();
It's common to bind a ListView to the List of non-trivial types.
Then you can handle SelectedItemChanged or something like that. You receive the whole object (in type object) which you can cast to your custom type and retrieve any properties you want

Retrieve comboBox displayed values

I am trying to retrieve the displayed values of all items present in a comboBox.
First case: if the comboBox has been filled using a DataSource:
comboBox.DataSource = myDataSet.Tables[0];
comboBox.DisplayMember = "value";
comboBox.ValueMember = "id";
...I use this code:
foreach (DataRowView rowView in comboBox.Items) {
String value = rowView.Row.ItemArray[1].ToString();
// 1 corresponds to the displayed members
// Do something with value
}
Second case: if the comboBox has been filled with the comboBox.Items.Add("blah blah"), I use the same code, except I have to look in the first dimension of the ItemArray:
foreach (DataRowView rowView in comboBox.Items) {
String value = rowView.Row.ItemArray[0].ToString();
// 0 corresponds to the displayed members
// Do something with value
}
Now I would like to be able to retrieve all values without knowing the scheme used to fill the comboBox. Thus, I don't know if I have to use ItemArray[0] or ItemArray[1]. Is it possible? How could I do that?
You can try something like this:
string displayedText;
DataRowView drw = null;
foreach (var item in comboBox1.Items)
{
drw = item as DataRowView;
displayedText = null;
if (drw != null)
{
displayedText = drw[comboBox1.DisplayMember].ToString();
}
else if (item is string)
{
displayedText = item.ToString();
}
}
The Combobox would be populated with the DataSource property in the first case. Therefore its DataSource won't be null. In the second case, it would be null. So you could do an if-else with (comboBox1.DataSource==null) and then accordingly use ItemArray[0] or ItemArray[1].
Leito, you could check to see if the DataSource is a DataTable or not to determine which action to take.
if (comboBox.DataSource is DataTable)
{
// do something with ItemArray[1]
}
else
{
// do something with ItemArray[0]
}

How to get value of checked item from CheckedListBox?

I have used a CheckedListBox over my WinForm in C#. I have bounded this control as shown below -
chlCompanies.DataSource = dsCompanies.Tables[0];
chlCompanies.DisplayMember = "CompanyName";
chlCompanies.ValueMember = "ID";
I can get the indices of checked items, but how can i get checked item text and value. Rather how can i enumerate through CheckedItems accessing Text and Value?
Thanks for sharing your time.
Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string comapnyName = castedItem["CompanyName"];
int? id = castedItem["ID"];
}
EDIT: I realized a little late that it was bound to a DataTable. In that case the idea is the same, and you can cast to a DataRowView then take its Row property to get a DataRow if you want to work with that class.
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (item as DataRowView).Row;
MessageBox.Show(row["ID"] + ": " + row["CompanyName"]);
}
You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (item as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("CompanyName");
MessageBox.Show(id + ": " + name);
}
You need to cast the item to access the properties of your class.
foreach (var item in checkedListBox1.CheckedItems)
{
var company = (Company)item;
MessageBox.Show(company.Id + ": " + company.CompanyName);
}
Alternately, you could use the OfType extension method to get strongly typed results back without explicitly casting within the loop:
foreach (var item in checkedListBox1.CheckedItems.OfType<Company>())
{
MessageBox.Show(item.Id + ": " + item.CompanyName);
}
You can iterate over the CheckedItems property:
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
MyCompanyClass company = (MyCompanyClass)itemChecked;
MessageBox.Show("ID: \"" + company.ID.ToString());
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx
foreach (int x in chklstTerms.CheckedIndices)
{
chklstTerms.SelectedIndex=x;
termids.Add(chklstTerms.SelectedValue.ToString());
}
To get the all selected Items in a CheckedListBox try this:
In this case ths value is a String but it's run with other type of Object:
for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
if (myCheckedListBox.GetItemChecked(i) == true)
{
MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());
}
}
Egypt Development Blog : Get value of checked item in CheckedListBox in vb.net
after bind CheckedListBox with data you can get value of checked items
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(i), DataRowView)
Dim XDR As DataRow = XDRV.Row
Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
Dim XValueMember As String = XDR(CheckedListBox1.ValueMember).ToString()
MsgBox("DisplayMember : " & XDisplayMember & " - ValueMember : " & XValueMember )
Next
now you can use the value or Display of checked items in CheckedListBox from the 2 variable XDisplayMember And XValueMember in the loop
hope to be useful.
I've already posted GetItemValue extension method in this post
Get the value for a listbox item by
index. This extension
method will work for all ListControl classes including
CheckedListBox, ListBox and ComboBox.
None of the existing answers are general enough, but there is a general solution for the problem.
In all cases, the underlying Value of an item should be calculated regarding to ValueMember, regardless of the type of data source.
The data source of the CheckedListBox may be a DataTable or it may be a list which contains objects, like a List<T>, so the items of a CheckedListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types.
GetItemValue Extension Method
We need a GetItemValue which works similar to GetItemText, but return an object, the underlying value of an item, regardless of the type of object you added as item.
We can create GetItemValue extension method to get item value which works like GetItemText:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);
Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.
This method is applicable on ComboBox and CheckedListBox too.
try:
foreach (var item in chlCompanies.CheckedItems){
item.Value //ID
item.Text //CompanyName
}
You may try this :
string s = "";
foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');

Setting dropdownlist selecteditem programmatically

I want to set the selecteditem attribute for an ASP.Net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.
Assuming the list is already data bound you can simply set the SelectedValue property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue variable would need to exist in the property specified within the DataValueField in your controls databinding.
UPDATE:
If the value of myValue doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.
Here is the code I was looking for :
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Or
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));
Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:
dropdownlist1.Text="Your Value";
This will work only if the value is existing in the data-source of the dropdownlist.
If you need to select your list item based on an expression:
foreach (ListItem listItem in list.Items)
{
listItem.Selected = listItem.Value.Contains("some value");
}
Just Use this oneliner:
divisions.Items.FindByText("Some Text").Selected = true;
divisions.Items.FindByValue("some value").Selected = true;
where divisions is a dropdownlist control.
Hope it helps someone.
var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);
OR
foreach (var listItem in ctx.Items)
listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);
Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
On load of My Windows Form the comboBox will display the ClassName column of my DataTable as it's the DisplayMember also has its ValueMember (not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
ddlemployee.DataSource = ds.Tables[0];
ddlemployee.DataTextField = "Employee Name";
ddlemployee.DataValueField = "RecId";
ddlemployee.DataBind();
ddlemployee.Items.Insert(0, "All");

Categories

Resources