The following code produces a ListView with the names of the customers:
private void displayDeliveries()
{
lstDeliveryDetails.Items.Clear();
foreach (Delivery d in mainForm.myDeliveries)
{
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
If I add, (d.DeliveryAddress), how can I get it to line up alongside the correct name?
I assume you mean that you want the delivery address to appear in the next column.
Set ListView's View property to Details.
Add two columns to the ListView's Collumns collection
Use the following code to populate the ListView
private void displayDeliveries()
{
lstDeliveryDetails.Items.Clear();
foreach (Delivery d in mainForm.myDeliveries)
{
ListViewItem item = lstDeliveryDetails.Items.Add(d.DeliveryName);
item.SubItems.Add(d.DeliveryAddress);
}
}
Assuming want to have the Address followed by the name in each list item:
foreach (Delivery d in mainForm.myDeliveries)
{
lstDeliveryDetails.Items.Add(d.DeliveryName + " " + d.DeliveryAddress);
}
This simply concatenates the DeliveryName with a space (" ") and then the DeliveryAddress strings.
Change the code in the for loop to:
ListViewItem item = lstDeliveryDetails.Items.Add(d.DeliveryName);
item.SubItems.Add(d.DeliveryAddress);
Related
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());
}
I am having an issue getting the checkedlistbox to display all selections in a message box for a windows application. I am only getting the last one selected to display. For example, I select "one, three, and five", only five displays.
Here is my code:
string display = "";
foreach (object selectedItems in clb.CheckedItems)
{
if (clb.SelectedItems.Count != 0)
{
display = "Items needed\n-----------\n\n\n" + selectedItems.ToString();
}
else
{
display = "No items selected";
}
}
MessageBox.Show(display, "Title");
Any ideas to point me in the right direction to accomplish this is appreciated.
Your error is in the loop that starts before the test of the number of items selected/checked. Your loop continues changing the value of the variable display at each loop. At the end the variable contains only the last item checked/selectd.
So, I assume that you want to display the checkeditems, not the selecteditems.
In any case you need to loop over the collection (ChekedItems in this case) and accumulate in a stringbuilder the item texts that you want to display.
string display = "";
// Every item in this collection is an item
// with CheckState = Checked or Indeterminate
if (clb.CheckedItems.Count != 0)
{
StringBuilder sb = new StringBuilder();
foreach(string item in clb.CheckedItems)
sb.AppendLine(item);
display = "Items needed\n-----------\n\n\n" + sb.ToString();
}
else
{
display = "No items checked";
}
MessageBox.Show(display, "Title");
If you really want to loop on the selecteditems, the code is the same, but just use the SelectedItems collection
you need to concat the selected items like display += or better to use Stringbuilder
display += " Items needed\n-----------\n\n\n" + selectedItems.ToString();
OR you can do as below
if(clb.CheckedItems.Count >0)
display = "Items needed\n-----------\n\n\n" + string.Join(",", clb.CheckedItems.Select( i=>i.ToString()));
else
display = "No items selected";
I'm using a enum with countries in a comboBox. All enums are in a class called Countries. Some of them has underscores like United_States_of_America. I need to remove those underscores before it shows in the comboBox?
My thought was to use Replace("_", " "), simple if it was a common string, but not so simple with a combobox! Therefore I would preciate some help to solve this? Thanks!
private void InitializeGUI()
{
// Fill comboBox with countries
cmbCountries.Items.AddRange(Enum.GetNames(typeof(Countries)));
}
Use the power of Linq :)
private void InitializeGUI()
{
// Fill comboBox with countries
cmbCountries.Items.AddRange(Enum.GetNames(typeof(Countries))
.Select(c => c.Replace("_", " "));
}
Or using a foreach:
private void InitializeGUI()
{
// Fill comboBox with countries
string[] countryNames = Enum.GetNames(typeof(Countries));
foreach (string countryName in countryNames)
{
cmbCountries.Items.Add(countryName.Replace("_", " "));
}
}
private void InitializeGUI()
{
// Fill comboBox with countries
cmbCountries.Items.AddRange(Enum.GetNames(typeof(Countries))
.Select(c => c.Replace("_", " ")));
}
This will create an IEnumerable<string>, that contains the names you selected from Enum (well done, working with Enum always seems horribly to me) and then replaces the underscore for each name.
You could also write this as:
countryNames = from country
in Enum.GetNames(typeof(Countries))
select country.Replace("_", " ");
cmbCountries.Items.AddRange(countryNames);
Enum.GetNames(typeof(Countries)).Select(x => x.Replace("_", " "));
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(',');
I have quite a few radiobuttonLists in my ASP.net webform. I am dynamically binding them using the method shown below:
public static void PopulateRadioButtonList(DataTable currentDt, RadioButtonList currentRadioButtonList, string strTxtField, string txtValueField,
string txtDisplay)
{
currentRadioButtonList.Items.Clear();
ListItem item = new ListItem();
currentRadioButtonList.Items.Add(item);
if (currentDt.Rows.Count > 0)
{
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
}
else
{
currentRadioButtonList.Items.Clear();
}
}
Now, I want to Display only the first Letter of the DataTextField for the RadioButton Item Text.
For example if the Value is Good I just want to Display G. If it Fair I want to display F.
How do I do this in C#
Thanks
You can't do what you want when you do the binding, so you have 2 options:
Modify the data you get from the table, before you do the binding.
After binding, go through each item and modify its Text field.
So, it you want to display "only the first Letter of the DataTextField for the RadioButton Item Text", you can do:
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Text.Substring(0, 1);
If I misunderstood you and you want to display the first letter of the Value field, you can replace the last two lines with:
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Value.Substring(0, 1);
You could add a property to the type that is being bound (the one that contains Good, Fair, etc.) and bind to this property. If you will always be using the first letter, you could make it like so (adding in null checks, of course):
public string MyVar { get; set; }
public string MyVarFirstChar
{
get { return MyVar.Substring(0, 2); }
}