Remove underscore from list of enums? - c#

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("_", " "));

Related

Binding dictionary to combobox in C#

I have this in Load of my form which contains combobox (cmbTip)
EventTypeRepository tip = new EventTypeRepository();
cmbTip.DataSource = new BindingSource(tip.FindAll(), null);
cmbTip.DisplayMember = "Value";
cmbTip.ValueMember = "Key";
(FindAll() is a method in EventTypeRepository which returns Dictionary(string, EventType>))
For some reason this displays MyProject.Model.EventType as all combobox items. I even added:
public string toString()
{
return _name + "(" + _id + ")";
}
in my EventType class, but it stills displays names as MyProject.Model.EventType (there are as many items as there are event types, so I think it works fine expect for displaying names). I have no idea how to fix this...
You should override ToString method (keep in mind C# is case-sensitive language):
public override string ToString()
{
return String.Format("{0}({1})", _name, _id);
}
Also it's better to set DisplayMember and ValueMember before you set DataSource.
If you ever find your self in a situation where you can't override ToString(), another option is to use the Format event built in to the combo box. First you must set FormattingEnabled to true on the combo box, then subscribe to the Format event and use code similar to the following.
private void cmbTip_Format(Object sender, ListControlConvertEventArgs e)
{
var item = (EventType) e.ListItem;
e.Value = String.Format("{0}({1})", Name, Id);
}
This assumes that _name and _id have corresponding public properties Name and Id.

How to select all items in a Listbox and concatenate them in ASP.NET C# Webform?

Right now I have
String myString = listbox1.Text.ToString();
However this only returns only the 1st item, even if I hit ctrl and select all of them.
Thanks for any help
Using an extension method, you can do this:
public static class Extensions
{
public static IEnumerable<ListItem> GetSelectedItems(this ListItemCollection items)
{
return items.OfType<ListItem>().Where(item => item.Selected);
}
}
Usage:
var selected = listbox1.Items.GetSelectedItems();
Now you can take the IEnumerable<ListItem> and convert that to a string array, then finally make it into a single string separated by semicolons, like this:
// Create list to hold the text of each list item
var selectedItemsList = new List<string>();
// Create list to hold the text of each list item
var selectedItemsList = selected.Select(listItem => listItem.Text).ToList();
// Build a string separated by comma
string selectedItemsSeparatedByComma = String.Join(",",
selectedItemsList.ToArray());
You are right, WebForms ListBox doesn't have the SelectedItems property. However, you can do
listBox.Items.OfType<ListItem>().Where(i => i.Selected);
That will give you the items you are looking for.
If you can't use LINQ, just do a foreach over listBox.Items, and do whatever you want when the item is Selected.

Add items to a ListBox and bind them to an item in another Listbox

My apologies in advance, I might have difficulty in making myself clear. I have searched, but the discussions were far to complicated for me to follow, and I just started dwelling in C#.
Project: C# WindowsForm / .NET 4.5 / Visual Studio 2012
Challenge:
I want to add items from a listbox to another listbox (I can do it easily with Lists and foreach loops), and make the end listbox show specific item depending on selections made in listbox2.
Explanation:
The selected items are to incorporate a group that I create in yet another listbox, so that if I select a handful of items in listbox1, I send them to listbox3, but they only should appear when I select a specific item in listbox2.
Imagine selecting games from a list, adding it to the "Nintendo" group in a new list, so they don't get mixed with the Sega ones when Sega is selected in listbox2.
I can add values in all listboxes, copy the ones I want from 1 to 3, but I am at a loss on how to make the selection respect the selection on 2.
I've read about databinding and etc, but the examples gives were too complicated (and maybe a bit of language barrier was present), is there a resource that can provide the simplest solution to a really small project?
Care to enlighten a fool using layman terms, please?
Thanks
EDIT:
Nice of you (whoever you were) to downvote my question. Fair enough. You could at least tell me what the problem was, or where the question was answered so I could resolve my problem. Wouldn't that be nice? I am a starter in C#, so it's only natural that the first question may seem ridiculous/lazy...
DataBinding would be the way to go. The main component to focus on is BindingSource. You could also investigate DataSets for your underlying data because they would give you some flexibility with filtering. But, if this is a small application, and if you're just learning, the following example might be a good start:
Drag a BindingSource for each of your listboxes onto your form. Then, connect each of the ListBox's DataSource properties to a corresponding BindingSource.
Here is an example code behind that shows how to bind your underlying data to each of the BindingSources which are in turn already bound to the listboxes:
namespace WindowsFormsApplication1
{
public class Game
{
public string Name { get; set; }
public string Group { get; set; }
}
public class Group
{
public string Description { get; set; }
}
public partial class Form1 : Form
{
List<Game> _allGames;
public Form1()
{
InitializeComponent();
_allGames = new List<Game>
{
new Game { Name = "Alpha", Group = "" },
new Game { Name = "Bravo", Group = "One" },
new Game { Name = "Charlie" , Group = "One"},
new Game { Name = "Delta", Group = "Two" }
};
bindingSource1.DataSource = _allGames;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Name";
var groups = new List<Group>
{
new Group { Description = "One" },
new Group { Description = "Two" },
new Group { Description = "Three" }
};
bindingSource2.DataSource = groups;
listBox2.DisplayMember = "Description";
listBox2.ValueMember = "Description";
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var group = listBox2.SelectedValue.ToString();
bindingSource3.DataSource = _allGames.Where(x => x.Group == group);
listBox3.DisplayMember = "Name";
}
}
}
All this code is doing is binding data to the BindingSource and telling each ListBox which property of the underlying data to display. This example ignores the mechanism that assign each item from listBox1 to the group in listBox2 because I assume you know how to do that or can figure that out.
The event handler for when listBox2 changes just gets which selection was made and creates a list of items from listBox1 that match that item, and then displays those items in listBox3.
For the sake of simplicity, lets assume the items bound to your listboxes are strings. Then you can use a dictionary to hold your group assignment (you have to hold it somewhere):
Dictionary<string, List<string>> listOfGroups = new Dictionary<string, List<string>>();
Where key is a name of group, and list of strings holds items in group.
Then, somewhere, you create a group to which you will be assigning values
void CreateGroup(string groupName)
{
listBox2.Items.Add(groupName);
if (!listOfGroups.ContainsKey(groupName)
listOfGroups.Add(groupName, new List<string>());
}
Then, you manage items in groups and add/remove them when, for example, selection on listBox2 changes:
string item = (string)listBox1.SelectedItem;
if(!listOfGroups.ContainsKey((string)listBox2.SelectedItem))
listOfGroups.Add((string)listBox2.SelectedItem,new List<string>());
((List<string>)listOfGroups[(string)listBox2.SelectedItem]).Add(item);
listBox3.Items.Add(item);
listBox1.Items.Remove(item);
And finaly:
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
listBox3.Items.Clear();
if (!listOfGroups.ContainsKey((string)listBox2.SelectedItem))
listOfGroups.Add((string)listBox2.SelectedItem, new List<string>());
listBox3.Items.AddRange(listOfGroups[(string)listBox2.SelectedItem].ToArray());
List<string> list = listOfAllItems.Where(a => !listBox3.Items.Contains(a)).ToList();
listBox1.Items.Clear();
listBox1.Items.AddRange(list.ToArray());
}
That's only an idea, though. If you're using DataSet, maybe you can just use linq (instead of a dictionary) to select items you want to display after selection in listbox2 changes.
You can save some kind of Dictionary, key is element in first ListBox first, and value is the item of the second ListBox.

Populating RadiobuttonList dynamically

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

List view new line for new values

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

Categories

Resources