Retrieve comboBox displayed values - c#

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]
}

Related

ListBox multiple Selection get all selected values

I'm having a problem since a while now an just can't find any solution that works for me. I have a ListBox which is filled up with a DataTable like
listbox.DataSource = table;
listbox.Displaymember = "Name";
listbox.ValueMember = "ID";
If I now select an item in my listbox I can get it out like:
listbox.SelectedValue.toString();
My Problem:
What can I do if I would like to have ALL selected Values from a ListBox where multiple selection is enabled and save them all in an array or something like that?!
I can't use SelectedItems cause that is not giving me the information I need.
Try this:
var lst = listBox1.SelectedItems.Cast<DataRowView>();
foreach (var item in lst)
{
MessageBox.Show(item.Row[0].ToString());// Or Row[1]...
}
Or if you want only iterate over the selected items you can use SelectedIndices property:
foreach (int i in listbox.SelectedIndices)
{
// listbox.Items[i].ToString() ...
}
Or:
foreach (var item in listbox.SelectedItems)
{
MessageBox.Show(item.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

how to get DisplayMemeber value from listbox by valuemember 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;

how to set the default value to the drop down list control?

I have a drop down list control on my web page. I have bind the datatable to the dropdownlist control as follows -
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
in the page load event i want to set the default value to the drop down list control from my other table field.
how to do this?
After your DataBind():
lstDepartment.SelectedIndex = 0; //first item
or
lstDepartment.SelectedValue = "Yourvalue"
or
//add error checking, just an example, FindByValue may return null
lstDepartment.Items.FindByValue("Yourvalue").Selected = true;
or
//add error checking, just an example, FindByText may return null
lstDepartment.Items.FindByText("Yourvalue").Selected = true;
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);
And in your cancel method:
lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");
And in your update method:
lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;

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