2009-01-31 54 views
7

我有一些在我的DB持有一个键值对引用表:GridView控件绑定下拉列表列出<keyvaluePair <int, string>>

类型的电话号码:

  • 1 - 首页
  • 2 - 工作
  • 3 - 移动
  • 4 - 传真

因此,我有一个类型的表,当他们在其他表中使用它们引用int值作为外键。当我将它们拉出来时,我一直将它们存储为正在使用它们的类中的keyvaluepair<int, string>项。

当我需要得到它们的列表时,我想我只是创建一个列表<>,而不是使用两种不同类型的数据类型来获取相同的数据。

当我使用edittemplate位时,需要在gridview中填充下拉列表时,我的问题已经到来。如果我使用数据源将其拉出,它将在文本中写入[1 Home],而不是将int作为值并将Home显示为文本。

我想我真的有一个多部分问题。

其中:

我是不是很笨?这是一个非常糟糕的方式来获取数据并将其存储(keyvaluepair部分)?我应该将它全部存储在数据表中吗?我不喜欢把它全部放在数据表中。我有我的DAL采取我的BLL,并试图封装一切作为对象或对象而不是所有的表格。大多数情况下,这一切都运行良好。

二:

如果我使用一些对象,而不是绑定到我的ObjectDataSource的下拉列表一个DataTable,我怎么可以设置当前选择的值,而不是有它只是在列表中的第一项选择?

编辑

正如指出的下方,我是一个傻瓜,只是需要设置DataValueField和DataKeyField。

要获得下拉列表绑定我只是不得不做:

SelectedValue='<%# DataBinder.Eval(Container, "DataItem.PhoneType.Key") %>' 

的原因,我没有看到一个马上是因为它没有出现在我的智能感知起来,但是当我手动键入它它工作。

回答

29

使用字典<整型,字符串>和设置您的下拉DataValueField到重点和DataTextField到价值

// 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(); 
+0

Dayam - 我想我有一个*易* 30点左右,但你打我给它。工作很好,答案很好! – 2009-01-31 21:04:03

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> 
相关问题