在ASP.NET中本地化动态绑定的DropDownList



我有一个下拉列表,它与数据库表'countries'绑定
下拉列表将countryname列作为其数据文本字段,将countrycode作为数据值字段
假设这个表有3个条目,它们分别具有如下所示的列值

印度IN
德国DE
美国US

我正在将文化转变为de-de
我知道对单个静态文本使用resx文件。现在,如何将多个datatextfield项同时本地化为deDE??

要做到这一点,您需要将表行集合与值上的资源文件中的值连接起来,然后将数据打包到一个自定义类型中,将DropDownList绑定到该类型。因此:

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

现在,将DropDownList的绑定属性更改为:

ddl.DataTextField = "Value";
ddl.DataValueField = "Key";

并绑定数据源:

ddl.DataSource = data;

编辑

要在不使用LINQ的情况下获得相同的结果,您需要将资源加载到字典中,然后遍历countries表来构建数据源;像这样的东西:

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

接下来,将dataSource绑定到您的DropDownList,一切就绪!

最新更新