Assign valuefield and textfield to listbox - c#

i develop a webpage in that i need to add value field and text field to listbox item
i tried the following code , but it's not working , Please help me to solve the issue .
Thanks in advance
string[] category = new string[100];
char[] delimeter = { '~' };
category = Convert.ToString(dtable.Rows[0].ItemArray[5]).Split(delimeter);
for (int h = 0; h < category.Length; h++)
{
ListItem lstitem = lstCategory.Items.FindByText(category[h]);
if (lstitem != null)
{
lstSelCategory.DataTextField = category[h];
lstSelCategory.DataValueField = lstitem.Value;
}
}
lstSelCategory.DataBind();
}

DataValueField and DataTextField are for assigning which properties are displayed and used as values for the assigned DataSource, NOT for adding items to the List.
EDIT:
It looks to me as though you're looping through some categories from a DataTable, finding a matching item in another ListBox and then trying to add that item to another ListBox... You should be using the Add method of the ListBox (if that's what the Control is).
lstSelCategory.Items.Add(new ListItem(category[h], lisitem.Value));

ListBox.DataTextField and ListBox.DataValueField are used in conjuction with ListBox.DataSource.
See this for further information.

Related

How can I set selected in a ComboBox, based on ValueMember?

I have a combobox with the following structure. Also, I am getting a fld_id from another source and based on that id I need to select the corresponding item in the ComboBox. How can I do that?
comboBoxCustomers.DataSource = customers;
comboBoxCustomers.ValueMember = "fld_id";
comboBoxCustomers.DisplayMember = "fld_name";
Example:
List could contain these items
fld_id fld_name
65 Item1
68 Item2
69 Item3
I need to set Item 68 as selected.
Use Following:
comboBoxCustomers.SelectedValue = fld_id(which you are getitng from another source)
I don't have enough reputation to post a comment. This:
comboBoxCustomers.SelectedValue = fld_id
works great :) But AFTER showing the form, otherwise it will fail.
if you use datasource of the combobox, you can cast the datasource back to the list, find the item and use that item to set the selected item:
var stores = cbxStores.DataSource as List<store>;
var store = stores.Where(w => w.store_code == _station.store_code).FirstOrDefault();
cbxStores.SelectedItem = store;
Simplest procdure I found for myself:
You can bind it into some function with perameters while funtion is called.
Hope it is going to help you guys:
int Idd = Convert.ToInt32(your value for the combobox you want to be selected);
for (int i = 0; i < myComboBox.Items.Count; i++)
{
myComboBox.SelectedIndex = i;
if (Convert.ToInt32( myComboBox.SelectedValue ) == Idd )
{break;}
}

asp.net ListItem: "Value" property returns the "Text" propery instead

In Windows Forms 4.5 I'm using a simple ListBox and adding items dynamically in code-behind like this:
for (int i = 0; i < rawshows.Count; i++)
{
var item = rawshows[i];
if (/* some comparisons I will not bore you with */)
{
ListItem li = new ListItem(item.ShowName, i.ToString());
shows.Add(li);
}
}
lbShows.DataSource = shows;
lbShows.DataBind();
As you can see, the text of the element is set to the item.ShowName (which is a string) and the value is set to the value of the i counter.
Everything seems fine, the list gets populated correctly. The problem is when I retrieve the selected item from the list. This:
lbShows.SelectedItem.Value
evaluates to the same value as
lbShows.SelectedItem.Text
(where lbShows is the listBox). Basically they both evaluate to the show name, instead of the number I set when populating the list.
Any clues on what I'm doing wrong?
Specify the DataTextField and the DataValueField" before calling .DataBind()
lbShows.DataTextField = "TextColumnName";
lbShows.DataValueField = "ValueColumnName";

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 add Tag and subitem in listview c#

I want to display tag and subitem in my listview , those items come by using while statement. here the code
int id = 0;
while ((line = sr.ReadLine()) != null)
{
id++;
string[] columns = line.Split(',');
ListViewItem item = new ListViewItem();
item.Tag = id;
item.SubItems.Add(columns[1]);
lv_Transactions.Items.Add(item);
}
subitems cab be displayed but the tag just appear blanks. Someone know to fix this please help me
To make the item have text, which I assume you want to show the 'id', you will want this:
item.Text = id.ToString();
The tag field is ignored by the control, and exists as a way of 'tagging' the source data to a control, so it can be retrieved later on (for example, when processing an event that was trigged by the control).
The Tag property is not displayable. You will need to add the contents of the tag as a subitem or otherwise embed it in the data you are showing to the user.
You have three choices on how to implement this:
1) ListViewItem item = new ListViewItem(id.ToString());
2) item.Text = id.ToString(); (this is effectively the same as 1)
3) item.SubItems(id.ToString()); if you want the id to appear in the list of subitems.
Update
SubItems will only work correctly if you have defined Columns in the ListView and have set the ListView's View to View.Details.
Assuming that you have not done this, the following line:
item.SubItems.Add(columns[1]);
should be modified to be:
item.Text = columns[1];

Getting Label Text of CheckBox from a CheckedListBox

I currently have a CheckedListBox with several boxes. I want to be able to test every Checkbox in the list to see if it's checked, and if it is, add it's text value (CheckBox.Text) to a List of strings.
Here is what I have:
for ( int i = 0; i < multiTaskChecks.Items.Count; i++ )
{
if ( multiTaskChecks.GetItemChecked(i) )
{
checkedMultiTasks.Add(multiTaskChecks.GetItemText(i));
}
}
Using this, GetItemText is returning 0, 1, 2, 3, etc instead of the text values that I'm after. I have also tried CheckedListBox.Text.IndexOf(i), CheckedListBox.Text.ToList(), each without any luck.
I just cannot get the label text of one of these CheckBoxes from the CheckedListBox. Any help with this would be really appreciated.
Firstly, you should be able to loop through the checked items only like so
foreach (var item in multiTaskChecks.CheckedItems)
{
}
then depending on the type of the item, get whatever property you want from it. Sounds like it is just a Text or you just want the string, so
foreach (var item in multiTaskChecks.CheckedItems)
{
checkedMultiTasks.Add(item.ToString());
}
or I prefer
checkedMultiTasks.AddRange(multiTaskChecks.CheckedItems.
OfType<object>().Select(‌​i => i.ToString()));
Try this:
for (int i = 0; i < multiTaskChecks.Items.Count; i++)
{
if (multiTaskChecks.GetItemChecked(i))
{
checkedMultiTasks.Add(multiTaskChecks.GetItemText(multiTaskChecks.Items[i]));
}
}
ListControl.GetItemText Method
NOTE There's a caution regarding DisplayMember for this method:
If the DisplayMember property is not specified, the value returned by GetItemText is the value of the item's ToString method. Otherwise, the method returns the string value of the member specified in the DisplayMember property for the object specified in the item parameter.
This should work:
var checkedMultiTasks = new List<string>();
foreach(var item in multiTaskChecks.CheckedItems) {
checkedMultiTasks.Add(item.ToString());
}

Categories