gridview将下拉列表绑定到List <keyvaluePair >
我的数据库中有许多表,它们包含对键值对的引用:
电话号码类型:
- 1 – 家
- 2 – 工作
- 3 – 移动
- 4 – 传真
等等
所以我有一个表的类型,当它们在其他表中使用时,它们将int值作为外键引用。 当我把它们拉出来时,我一直将它们存储为使用它们的类中的keyvaluepair
项。
当我需要获取它们的列表时,我认为我只是创建它们的List 而不是使用两种不同类型的数据类型来获得相同的数据。
当我使用edittemplate位时,我需要在gridview中填充下拉列表时,我的问题已经到了。 如果我使用数据源将其拉出来,它将在文本中写入[1 Home],而不是将int作为值,将Home作为要显示的文本。
我想我真的有一个多部分问题。
一:
我是傻瓜吗? 这是一个非常糟糕的方法来获取数据并存储它(keyvaluepair部分)? 我应该将它们全部存储在数据表中吗? 我不喜欢把它全部放在数据表中。 我把我的DAL带到我的BLL并尝试将所有内容封装为对象或List
的对象而不是所有内容的表。 大部分时间这都运作良好。
二:
如果我使用某个对象而不是数据表绑定到下拉列表的objectdatasource,我该如何设置当前选择的值,而不是让它只选择列表中的第一项?
编辑
正如下面所指出的,我是一个白痴,只需要设置DataValueField和DataKeyField。
要使下拉列表绑定,我必须这样做:
SelectedValue=''
我没有立刻看到它的原因是因为它没有出现在我的intellisense中,但是当我手动键入它时,它起作用了。
使用Dictionary
// A sample dictionary: var dictionary = new Dictionary(); 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 dropDown.DataBind();
和我的自定义方法
// 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 GetAllServiceTypeName() { Dictionary dataSource = new Dictionary(); 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