Reputation: 131
I have a dropdownlist which binds with a database table 'countries'
The dropdownlist takes column countryname as its datatextfield and countrycode as datavaluefield.
Suppose this table has 3 entries which have respective column values as given below.
India , IN
Germany , DE
America , US
and I am changing the culture to de-DE
I know to use resx file for a single static text.
Now, how can I localize the multiple datatextfield items to de-DE simultaneously??
Upvotes: 2
Views: 1600
Reputation: 9576
To do this you need to join the collection of table rows with the values from the resource file on the value, then pack the data into a custom type to which you'll bind the DropDownList
. So:
var tableRows = table.Rows.Cast<DataRow>();
var resourceStrings = YourResourceClass.ResourceManager
.GetResourceSet(culture: CultureInfo.CurrentUICulture,
createIfNotExists: false,
tryParents: true)
.Cast<DictionaryEntry>();
var data = tableRows
.Join(resourceStrings,
row => row["countrycode"].ToString(),
resource => resource.Key,
(row, resource) => new KeyValuePair<string, string>(
row["countrycode"].ToString(),
resource.Value.ToString()))
.ToArray();
Now, change binding properties of your DropDownList
to:
ddl.DataTextField = "Value";
ddl.DataValueField = "Key";
And bind the datasource:
ddl.DataSource = data;
EDIT
To achieve the same result without using LINQ you'll need to load the resources into a dictionary and then iterate over the counties table to build the data source; something like this:
var resources = new Dictionary<string,string>();
var resourceSet = YourResourceClass.ResourceManager.GetResourceSet(
CultureInfo.CurrentUICulture, false, true);
foreach(DictionaryEntry kvp in resourceSet)
{
resources[kvp.Key] = kvp.Value.ToString();
}
var dataSource = new List<KeyValuePair<string, string>>();
foreach(DataRow in table.Rows)
{
var countryCode = row["countrycode"].ToString();
if(resources.ContainsKey(countryCode))
{
dataSource.Add(new KeyValuePair<string, string>(
countryCode,
resources[contryCode]));
}
}
Next, bind the dataSource
to your DropDownList and you're all set!
Upvotes: 2