帮我看一下comboBox的SelectedValue问题

menganafff 2009-01-19 09:38:56
手动写入一个combobox控件:
comboBox1.Items.Insert (0,"请选择");
comboBox1.Items.Insert (1,"根目录");
comboBox1.SelectedIndex=0;

我想取出该控件的SelectedValue,可是提示末将对象引用设置到对象的实例,这说明写入的时候没有指定SelectedValue,那么该怎么样指定呢?

多谢了
...全文
133 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
menganafff 2009-01-19
  • 打赏
  • 举报
回复
多谢大家
CutBug 2009-01-19
  • 打赏
  • 举报
回复
{            
comboBox1.Items.Insert(0, new ComboBoxItem("0","请选择"));
comboBox1.Items.Insert(1, new ComboBoxItem("1","根目录"));
comboBox1.SelectedIndex = 1;

MessageBox.Show(comboBox1.SelectedItem.ToString());//根目录
MessageBox.Show(((ComboBoxItem)comboBox1.SelectedItem).Value);//1

}

internal class ComboBoxItem:Object
{
private string value;
private string text;
public ComboBoxItem(string _value, string _text)
{
value = _value;
text = _text;
}

public string Text
{
get { return text; }
}

public string Value
{
get { return value; }
}

public override string ToString()
{
return text;
}

}

bdmh 2009-01-19
  • 打赏
  • 举报
回复
SelectedValue 需要额外分配的,不是初始就有的
david_anwei 2009-01-19
  • 打赏
  • 举报
回复
DataTable dt = new DataTable() ;
[align=left]dt.Columns.Add("name",typeof(string)) ;
dt.Columns.Add("id",typeof(int)) ;

DataRow row ;

row = dt.NewRow() ;
row["id"] = (int)ZhiLingDanType.TuoYunJianBaoZhuangDan ;
row["name"] = "托运件包装单" ;
dt.Rows.Add(row) ;

row = dt.NewRow() ;
row["id"] = (int)ZhiLingDanType.PaiSongChuKuDan ;
row["name"] = "派送出库单" ;
dt.Rows.Add(row) ;


this.DataSource = dt ;
this.DisplayMember = "name" ;
this.ValueMember = "id" ;

this.SelectedValue = selectedID ;
feiyun0112 2009-01-19
  • 打赏
  • 举报
回复
SelectedValue 属性

获取或设置由 ValueMember 属性指定的成员属性的值。


看看MSDN


*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码)

http://feiyun0112.cnblogs.com/
lovehongyun 2009-01-19
  • 打赏
  • 举报
回复
可以用1楼的办法.

从数据取设置ValueMember ...那个是可以的.
menganafff 2009-01-19
  • 打赏
  • 举报
回复
不会吧,如果是从数据库绑定的话,我们可以这样设置:
string sql1="select id,name from addressmanage where type='2'";
DataTable dt1=DB.DataAccess.GetSqlData (sql1);
comboBox2.ValueMember = "id";
...........

取的时候直接取comboBox2.SelectedValue就行了

如果不是从数据库绑定的话,是手写的话,就不能用comboBox2.ValueMember这样的方式设置了吗?
sprc_lcl 2009-01-19
  • 打赏
  • 举报
回复
存到变量内,控件不认value

如:
ArrayList cbValues = new ArrayList();//定义到外面private ArrayList cbValues = new ArrayList();
this.comboBox1.Items.Insert(0, "");
cbValues.Insert(0, value0);

//取Value的话就去cbValues取

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧