winform下的程序,想实现这么个功能:一个下拉列表,比如显示的是民族,其值是民族代码,旁边有个对应的文本框。想实现在文本框内输入民族代码,下拉列表就改为选中相应的民族。
这个功能需要对下拉列表的value值进行遍历。我的下拉列表是直接绑定数据集,只能有个SelectedValue属性,无法遍历。在CSDN、GOOGLE、BAIDU、CODEPROJECT一通翻,也没找到能直接遍历的办法,最后看见有人是用类实现的。
首先是CSDN的一个帖子:
http://topic.csdn.net/t/20050307/18/3831619.html
里面有个回复提到了,但是说得不够详细。看完它后,我觉得似乎没必要用类,于是试着写了个structure,但是不行,下拉列表根本无法正常显示。
后来又看到了下面这个:
http://dev.csdn.net/develop/article/32/32319.shtm
----------------------------
今天好像特别提不起精神来写程序。
这几天公司的活和私活都不是很多,所以上班的上午也被我用来写这个小软件,因为以前一直从事WEB开发,vs。net也是用来写ASP.NET的,最近才开始写WINFORM,所以有很多小的问题搞得不是很清楚,所以整个程序看起来比较乱,昨天困扰了我很久的竟然是ComboBox,我想当然的拿它和Web Control中的DropDownList来对比,所以我一直不知道Value在ComboBox是什么?ValueMember只能用来绑定,而selectedvalue也只能取来自数据库绑定的值,我只能定义一个类来实现我手动增加ComboBox的Item
public class ComboBoxItem
{
private string _text=null;
private object _value=null;
public string Text{get{return this._text;} set{this._text=value;}}
public object Value{get {return this._value;} set{this._value=value;}}
public override string ToString()
{
return this._text;
}
}
这段代码我是从网上找的,然后使用
ComboBoxItem newItem = new ComboBoxItem();
newItem.Text = “abc”;
newItem.Value = “1”;
ComboBox1.Items.Add(newItem);
取值的时候又没有注意到selectedvalue是取自ValueMember所以忘了强制转换类型,浪费了我一小时的时间。。
取值使用方法:
ComboBoxItem myItem = (ComboBoxItem)ComboBox1.Items[0];
string strValue = myItem.Value;
其实很多地方和WebForm很多的不一样,所以一直还是处于摸索阶段。
-------------------------------
没办法,把这个COPY过来,做了一点改进:加了index属性,这样不仅可以用add方法添加,也可以用insert方法了,OK,一宿总算没白熬。关键在于那个重写的ToString()。
我的类:
-------------------------------
Public Class ComboBoxItem
Private _text As String = ""
Private _value As Object = Nothing
Private _index As Integer = -1
Public Sub New(ByVal intIndex As Integer, ByVal strText As String, ByVal objValue As Object)
_text = strText
_value = objValue
_index = intIndex
End Sub
Public Property Text() As String
Get
Return _text
End Get
Set(ByVal Value As String)
_text = Value
End Set
End Property
Public Property Value() As Object
Get
Return _value
End Get
Set(ByVal Value As Object)
_value = Value
End Set
End Property
Public Property Index() As Integer
Get
Return _index
End Get
Set(ByVal Value As Integer)
_index = Value
End Set
End Property
Public Overrides Function ToString() As String
Return _text
End Function
End Class
-------------------------------