2009-01-31 34 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> 
相關問題