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

Localize a dynamically binding DropDownList in ASP.NET

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

印度印度
德国 , 德国
美国美国

我正在将文化更改为 de-DE
我知道将 resx 文件用于单个静态文本。 现在,如何将多个数据文本字段项目同时本地化为 de-DE??

为此,您需要将 table 行的集合与资源文件中的值连接起来,然后将数据打包到自定义类型中,您将绑定 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 的情况下获得相同的结果,您需要将资源加载到字典中,然后遍历各个县 table 以构建数据源;像这样:

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,一切就绪!