Getting Label Text of CheckBox from a CheckedListBox - c#

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

Related

How to get ValueMembers of CheckedListBox Checked Items?

I have a CheckedListBox named Itemlist. And its DataSource is a data table. I have set a DisplayMember as "Name" , and a ValueMember as "NameInt". Is there a reliable way that I can loop through this CheckedListBox and get the ValueMember of the checked items?
Assuming a public property holding your DataTable:
public DataTable Table { get; set; }
Noting the CheckedListBox is named Itemlist (in case edit's occur) - and assuming NameInt is of type int, we can loop through the checked items, grab the index, then get the associated ValueMember directly from the source:
List<int> checkedValueMembers = new List();
foreach (int index in Itemlist.CheckedIndices)
{
checkedValueMembers.Add(Table.Rows[index].Field<int>("NameInt"));
}
Note: I was adding the values to a list as an example, but that should give you the general idea..
for (int i = 0; i < dataSet.tblResources.Rows.Count; i++)
{
clbResources.Items.Add(new Thing()
{
Key = dataSet.tblResources.Rows[i]["Key"].ToString(),
Value = dataSet.tblResources.Rows[i]["Description"].ToString()
}, isChecked);
}
This is from one of my projects. Change accordingly.

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 get the selected values of Listbox in c#

i had bind the listbox where datasource of listbox is list.how can i get the selected value of selected list item in listbox.my sample code as follows
pdfList = attendanceDetailsPresenter.GetPredefinedDetails();
this.lstCompanies.DataSource = pdfList;
this.lstCompanies.DisplayMember = "CompanyName";
this.lstCompanies.ValueMember = "CompID";
this.lstDepartments.BindingContext = new BindingContext();
this.lstDepartments.DataSource = pdfList;
this.lstDepartments.DisplayMember = "DepartmentName";
this.lstDepartments.ValueMember = "DeptID";
if (lstCompanies.SelectedItems.Count < 0)
{
MessageBox.Show("Please Select Any one Company");
return attendanceCalculationDetailsDataList;
}
else
{
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}
}
can anyone solve my problem please.
First of all, the Count of a list can never be less than zero. It's always >= 0.
Then, when you data-bind your list, the items usually are of type DataRowView (which you should be able to verify by debugging your application). If that is right, you should have to cast each selected item to DataRowView and then cast the value of its Row property to the type you expect.
I just noticed that in the following loop you're not even using the selected items, but always the SelectedValue:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}
Try changing this to:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(((<WhatEverClassYouUse>)lstCompanies.SelectedItems[i]).CompanyID);
}
Explanation: If more than one item in the list are selected, the items are added to the SelectedItems collection. You can iterate these items. Each item will be an object of DataRowView (when data bound to a DataTable or DataView) or a class in a collection.
As you didn't tell us the type of objects returned by GetPredefinedDetails, I substituted it with WhatEverClassYouUse. Cast this to the right type.

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;

Assign valuefield and textfield to listbox

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.

Categories