any better way of Sorting my dropdownlist
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));
drpC开发者_如何学编程ountryRegion.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.
精彩评论