将List<keyvaluePair<int, string>>绑定到GridView下拉列表

7
我在我的数据库中有许多表,其中保存了键值对的引用:
电话号码类型:
1 - 家庭
2 - 工作
3 - 移动
4 - 传真
等等
所以我有一个表来存储这些类型,并且当它们在其他表中使用时,它们将int值作为外键引用。当我取出它们时,我一直在将它们存储为使用它们的类中的keyvaluepair项。
当我需要获取它们的列表时,我想我只需创建一个List<>而不是使用两种不同类型的数据类型来获取相同的数据。
当我在使用edittemplate时需要填充一个gridview中的dropdownlist时,我的问题就出现了。如果我使用数据源来提取它,它会在文本中写[1 Home],而不是将int作为值和Home作为要显示的文本。
我想我确实有一个多部分的问题。
第一个:
我是愚蠢的吗?这是获取数据并存储的非常糟糕的方法吗(keyvaluepair部分)?我应该只将其全部存储在datatable中吗?我不想将所有内容都放在datatable中。我有我的DAL与我的BLL交谈,并尝试封装所有内容作为对象或List<>的对象,而不是所有内容的表。大多数时候这很有效。
第二个:
如果我使用某个对象而不是datatable来绑定到我的objectdatasource中的dropdownlist,如何设置当前选择的值,而不是只选择列表中的第一项?
编辑:
正如下面所指出的那样,我很傻,只需要设置DataValueField和DataKeyField即可。
要使dropdownlist绑定,我只需执行:
SelectedValue='<%# DataBinder.Eval(Container, "DataItem.PhoneType.Key") %>'

我之所以没有立即看到它,是因为它没有出现在我的智能感知中,但当我手动输入时,它起作用了。

2个回答

32

使用一个Dictionary<int, string>,并将你的DropDown的DataValueField设置为Key,将DataTextField设置为Value

    // A sample dictionary:
    var dictionary = new Dictionary<int, string>();
    dictionary.Add(1, "Home");
    dictionary.Add(2, "Work");
    dictionary.Add(3, "Mobile");
    dictionary.Add(4, "Fax");

    // Binding the dictionary to the DropDownList:
    dropDown.DataTextField = "Value";
    dropDown.DataValueField = "Key";
    dropDown.DataSource = dictionary;  //Dictionary<int, string>
    dropDown.DataBind();

我靠 - 我以为这题很简单,但你比我先做出来了。干得好,回答得不错! - Mark Brittingham
1
谢谢。这很棒,它还可以与一个List<>一起使用。但我想在某些方面,这就是字典的作用了... - Jon
我忘记设置DataValueField和DataTextField。导致我的下拉列表的值和显示文本相同。谢谢! - Kevin Ng

0

这是我的自定义方法

// Define enum
public enum ServiceType : int
{
    MinimumService = 1,
    NormalService = 2,
    VipService = 99
}

// custom method to get my custom text name for each enum type
public string GetServiceTypeName(ServiceType serviceType)
{
    string retValue = "";
    switch (serviceType)
    {
        case ServiceType.Print:
            retValue = "We have some services for you";
            break;
        case ServiceType.BookBinding:
            retValue = "We ar glad to meet you";
            break;
        default:
            retValue = "We alywas are ready to make you happy";
            break;
    }
    return retValue;
}

// making dictionary (key and value) for dropdown datasource
public static Dictionary<string, int> GetAllServiceTypeName()
{
    Dictionary<string, int> dataSource = new Dictionary<string, int>();

    foreach (int item in Enum.GetValues(typeof(ServiceType)))
        dataSource.Add(GetServiceTypeName((ServiceType)item), item);

    return dataSource;
}


   // bind the dropdown to dictionary
    ddlServiceType.DataSource = GetAllServiceTypeName();
    ddlServiceType.DataBind();

   // aspx markup code sample
    <asp:DropDownList ID="ddlServiceType" runat="server" 
        DataTextField="Key" DataValueField="Value">
    </asp:DropDownList>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接