any better way of Sorting my dropdownlist - c#

After I retrieve the country names in English, I convert the country names to localized versions, I need to sort those names again, so I used SortDropDownList. Here, after I sort my DropDownList Items, I am losing the PrivacyOption attribute I set.
Can someone suggest solutions to sort my DropDownList while also retaining the PrivacyOption attribute?
I am using asp.net4.0 along with C# as CodeBehind:
int iCount = 1;
//fetch country names in English
List<CountryInfo> countryInfo = ReturnAllCountriesInfo();
foreach (CountryInfo c in countryInfo)
{
if (!string.IsNullOrEmpty(Convert.ToString(
LocalizationUtility.GetResourceString(c.ResourceKeyName))))
{
ListItem l = new ListItem();
l.Text = Convert.ToString(
LocalizationUtility.GetResourceString(c.ResourceKeyName));
l.Value = Convert.ToString(
LocalizationUtility.GetResourceString(c.ResourceKeyName));
//True /False*
l.Attributes.Add("PrivacyOption", *Convert.ToString(c.PrivacyOption));
drpCountryRegion.Items.Insert(iCount, l);
iCount++;
}
//sorts the dropdownlist loaded with country names localized language
SortDropDownList(ref this.drpCountryRegion);
}
And the code to SortDropDownList items:
private void SortDropDownList(ref DropDownList objDDL)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();
foreach (ListItem li in objDDL.Items)
{
textList.Add(li.Text);
}
textList.Sort();
foreach (object item in textList)
{
string value = objDDL.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
objDDL.Items.Clear();
for (int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(),
valueList[i].ToString());
objDDL.Items.Add(objItem);
}
}

Sort the data before you populate the DropDownList.
IEnumerable<Country> sortedCountries = countries.OrderBy(
c => LocalizationUtility.GetResourceString(c.ResourceKeyName));
foreach (Country country in sortedCountries)
{
string name = LocalizationUtility.GetResourceString(country.ResourceKeyName);
if (!string.IsNullOrEmpty(name))
{
ListItem item = new ListItem(name);
item.Attributes.Add(
"PrivacyOption",
Convert.ToString(country.PrivacyOption));
drpCountryRegion.Items.Add(item);
}
}

Have you thought about sorting the information in a SortedDictionary instead of a List?

I am not quiet sure if I understand how your implementation of SortDropDownList method works. However, I can suggest using a List<KeyValue<string, string>> to bind to your DropDownList. You can use the English part and local part in your KeyValuePair and sort accordingly.

Related

How to make listitems highlighted/selected in the listbox from an array?

i have a listbox with 3 listitems (bob, peter, john). How do I make the listitems selected/highlighted depending on what is applicable in the array. Currently I have this:
string names = reader["staffName"].ToString();
string[] selectedName = names.Split(',');
for (int i = 0; i < selectedName.Length; i++)
{
lbName.SelectedIndex = lbName.Items.IndexOf(lbName.Items.FindByValue(selectedName[i]));
}
But it only highlights the last item in the array. e.g. selectedName consist of 2 names (bob and john), but only john is highlighted
First you should check if lbName.SelectionMode is ListSelectionMode.Multiple
then you should the following
string names = reader["staffName"].ToString();
string[] selectedName = names.Split(',');
lbName.SelectedIndex = -1;
foreach (var name in selectedName)
{
lbName.Items.First(item => item.Value == name).Selected = true;
}

Add to array list from listbox selected item does not work properly

I have a program where I am trying to move items from one arrayList to another via a listbox and then print out the info in an XML, but the error I have is when I am adding it often certain times the values would repeat, when there are no repeats.
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(new RandomClass(var1, var2, var3, var4, var5, var6, var7));
foreach (object o in list1)
{
RandomClass m = (RandomClass)o;
selectionBox.Items.Add(m);
}
This is my initialization code.
bool req = true;
if (selectionBox.SelectedItem != null)
{
Count++;
errorLabel.Text = "";
for (int i = 0; i < selectionBox.Items.Count; i++)
{
if (selectionBox.GetSelected(i) == true)
{
RandomClass m = selectionBox.SelectedItem as RandomClass;
if (m.var2 == ((RandomClass)selectionBox.Items[i]).var2)
{
list2.Add(list1[i]);
}
}
}
}
else
{
errorLabel.Text = "Error";
}
Here is where I add to another array list. However as I said often the item would repeat and not be different, how can I resolve this problem?
Try clearing the second list each time you scan and add items from the first list.
list2.Clear();
for (int i = 0; i < selectionBox.Items.Count; i++)
....
I have fixed this problem using a list with my class, and there does not seem to be a problem.
List<RandomClass> list2 = new List<RandomClass>();
And then when adding I just simply put the following in the if statement
list2.Add(m);

adding items to columns/rows in listview using foreach

I am into day 5 of learning c#, and am trying to figure out how to fill/re-fill a ListView control, containing 10 rows and 12 columns, using a foreach loop. I have coded the functionality I'm after in C.
void listPopulate(int *listValues[], int numberOfColumns, int numberOfRows)
{
char table[100][50];
for (int columnNumber = 0; columnNumber < numberOfColumns; ++columnNumber)
{
for (int rowNumber = 0; rowNumber < numberOfRows; ++rowNumber)
{
sprintf(&table[columnNumber][rowNumber], "%d", listValues[columnNumber][rowNumber]);
// ...
}
}
}
Here is what I have figured out so far:
public void listView1_Populate()
{
ListViewItem item1 = new ListViewItem("value1");
item1.SubItems.Add("value1a");
item1.SubItems.Add("value1b");
ListViewItem item2 = new ListViewItem("value2");
item2.SubItems.Add("value2a");
item2.SubItems.Add("value2b");
ListViewItem item3 = new ListViewItem("value3");
item3.SubItems.Add("value3a");
item3.SubItems.Add("value3b");
....
listView1.Items.AddRange(new ListViewItem[] { item1, item2, item3 });
}
I'm assuming that I would have to do the creation of the list items in a separate step. So my question is: there must be a way to do this in C# with a for or foreach loop, no?
I am not sure if I understood you correctly, but here's i think what you need...
Actually it depends on your DataSource which you are using to fill up the ListView.
Something like this (I am using Dictioanry as a DataSource here) -
// Dictinary DataSource containing data to be filled in the ListView
Dictionary<string, List<string>> Values = new Dictionary<string, List<string>>()
{
{ "val1", new List<string>(){ "val1a", "val1b" } },
{ "val2", new List<string>(){ "val2a", "val2b" } },
{ "val3", new List<string>(){ "val3a", "val3b" } }
};
// ListView to be filled with the Data
ListView listView = new ListView();
// Iterate through Dictionary and fill up the ListView
foreach (string key in Values.Keys)
{
// Fill item
ListViewItem item = new ListViewItem(key);
// Fill Sub Items
List<string> list = Values[key];
item.SubItems.AddRange(list.ToArray<string>());
// Add to the ListView
listView.Items.Add(item);
}
I have simplified the code for your understanding, since there several ways to iterate through a Dictionary...
Hope it helps!!
You do this almost exactly the same as in C. Just loop through the collection...
int i = 0;
foreach (var column in listValues)
{
var item = new ListViewItem("column " + i++);
foreach (var row in column)
{
item.SubItems.Add(row);
}
listView1.Items.Add(item);
}
It's hard to provide a real example without seeing what your collection looks like, but for an array of arrays this will work.

how to add the selected item from a listbox to list <string> in c#

how to add the selected item from a listbox to list to get the username that are selected
my code:
List<String> lstitems = new List<String>();
foreach (string str in lstUserName.SelectedItem.Text)
{
lstitems.Add(str);
}
it show me error saying cannot convert char to string.... how to add the items to list or array
You need to use the SelectedItems property instead of SelectedItem:
foreach (string str in lstUserName.SelectedItems)
{
lstitems.Add(str);
}
EDIT: I just noticed this is tagged asp.net - I haven't used webforms much but looking at the documentation it seems this should work:
List<string> listItems = listBox.GetSelectedIndices()
.Select(idx => listBox.Items[idx])
.Cast<string>()
.ToList();
I note that you're using ASP.
For standard C# the following would work:
List<string> stringList = new List<string>();
foreach (string str in listBox1.SelectedItems)
{
stringList.Add(str);
}
If there's only one selected item:
List<String> lstitems = new List<String>();
lstitems.Add(lstUsername.SelectedItem.Value);
Here's a method for getting multiple selections since System.Web.UI.WebControls.ListBox doesn't support SelectedItems:
// Retrieve the value, since that's usually what's important
var lstitems = lstUsername.GetSelectedIndices()
.Select(i => lstUsername.Items[i].Value)
.ToList();
Or without LINQ (if you're still on 2.0):
List<string> lstitems = new List<string():
foreach(int i in lstUsername.GetSelectedIndices())
{
lstitems.Add(lstUsername[i].Value);
}
You can also do this
List<String> lstitems = new List<String>();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
lstitems.Add(ListBox1.Items[i].Value);
}
If you are using a button to add selected 'item' in string list, just do this.
private void button1_Click(object sender, EventArgs e)
{
List<string> selectedItems = new List<string>();
string item = listBox1.SelectedItem.ToString();
if (!selectedItems.Contains(item))
{
selectedItems.Add(item);
}
}
You can do this in one operation:
IEnumerable<string> groupList = groupsListBox.SelectedItems.Cast<string>();
It will always work for custom objects too:
IEnumerable<CustomObject> groupList = groupListBox.SelectedItems.Cast<CustomObject>();

Better way to bind generic List to DomainUpDown control (text spin control)

I have been trying to find out how to bind data to a
System.Windows.Forms.DomainUpDown() control.
Currently I have only come up with:
private void Init()
{
List<string> list = new List<string>();
list = get4000Strings(); //4000 items
foreach (string item in list)
{
domainUpDown1.Items.Add(item);
}
}
private List<string> get4000Strings()
{
List<string> l = new List<string>();
for (int i = 0; i < 4000; i++)
{
l.Add(i.ToString());
}
return l;
}
The DomainUpDown.Items collection has an AddRange() method that takes an ICollection (implemented by List<T>), so you could just do
private void Init() {
List<string> list = new List<string>();
list = get4000Strings(); //4000 items
domainUpDown1.Items.Clear();
domainUpDown1.Items.AddRange(list);
}
However, if you have that much items to show, I would suggest you use a ComboBox having DropDownStyle set to DropDownList.
It will allow you to databind directly to the list (e.g. comboBox1.DataSource = list;), especially if the list changes often, as you won't have to refill the ComboBox each time, just change the datasource...

Categories