2009-07-21 33 views
2

我有一個組合框,但我希望它顯示來自數據源的兩個不同的列值。所以不要簡單地用「rowid」填充它(可能的值爲「1」,「2」,「3」等),而是希望它顯示「letter」(「a」,「b」,「 c「)列,但在同一個框中。C#ASP.NET - 填充組合框以顯示數據源中的兩個值?

它發送的實際值可以只是該rowid值,但爲了用戶友好的目的,我需要兩者。

this.comboBox1.DataSource = this.tblIDSourceBindingSource; 
this.comboBox1.DisplayMember = "rowid"; 
this.comboBox1.FormattingEnabled = true; 
this.comboBox1.Name = "comboBox1"; 
this.comboBox1.ValueMember = "rowid"; 

正如你所看到的,它顯示「rowid」。試圖告訴它顯示「字母」另外拋出一切。

+0

所以你想讓下拉菜單顯示2列而不是標準1列? – 2009-07-21 15:09:00

+0

您可以先連接2列並綁定到該列,而不是您當前的數據源。 – 2009-07-21 15:09:41

+0

2我想,列將是有意義的! Stan R .:如果你的意思是修改數據庫,我不能。 – scrot 2009-07-21 15:16:15

回答

2

假設:你不能只顯示「字母」並完成它。

改變你的PROC來使,而不是

select rowid, letter, blah 
from table 

這樣做

select rowid + ' ' + letter as display, rowid, letter, blah 
from table 

或者,如果你不喜歡的空間,使用您的選擇(管的分隔符(S) ,斜線,在括號中包裝rowid等)。

然後使用「display」作爲您的DisplayMember。

p.s.如果rowid是一個int,則需要使用CAST或CONVERT使其成爲nvarchar或varchar。

p.p.s.如果你不能改變你的PROC,那麼長的方法是創建一個輕實體相同的回報率,但增加了一個只讀屬性調用顯示其得到的是類似

return string.Format("{0}{1}{2}", this.rowid, delimiterOfChoice, this.letter); 

或某事那種性質。

那麼只需使用這些實體的集合作爲您的bindingsource。

+0

爲什麼downvote?這似乎是一個完美可行的解決方案。請評論,如果你downvote某人的回答 – 2009-07-21 15:46:10

+0

驅動器downvote。我投了票。 – scrot 2009-07-21 15:48:00

+0

也許有人貶低別人,讓自己的答案最高。 – scrot 2009-07-21 15:49:08

0

作爲一種快速和骯髒的黑客攻擊,一旦數據從數據庫填充後,您應該能夠向數據表中添加新列。在表格中循環建立您想要爲每行顯示的字符串並將其粘貼到新列中。然後將其綁定爲顯示此值。

+0

爲什麼不選擇字母+''+ rowid?或字母+'/'+ rowid?沒有必要擁有該列,因爲它與數據本身無關。 (沒有downvote順便說一句) – 2009-07-21 15:47:36

+0

也沒有我正如我所說,這可能是最高的投票吸氣劑的做法。 – scrot 2009-07-21 15:50:16

+0

我做了投票 - 開幕行是「快速和骯髒的黑客」shouhld已經足夠。你會添加很多問題,需要維護新的數據庫列,爲什麼不使用那裏的工具?另外數據源並不總是=數據庫 – Adrian 2009-07-21 15:55:35

3

您需要在此改變Format事件

// FormatString property is shown in the designer, so you can provide 
    // some designer support. If you are not using the desinger then you 
    // either set it in the form/control ctor, or use a string directly 
    // in the Format event. 
    ListControl.FormatString = "{0}/{1}" ; 

    private void listBoxCategory_Format(object sender, ListControlConvertEventArgs e) 
     { 
      e.Value = string.Format(((ListBox)sender).FormatString, 
       ((ClassOfListItem)e.ListItem).LongName, 
       ((ClassOfListItem)e.ListItem).Key); 
    } 
+0

+1,簡而言之。 – 2009-07-21 15:49:54

0

你應該一個新的屬性添加到您的類/頁面,需要在您的數據源兩個字段的值,將DisplayMember分配給該屬性