如何从Combobox中设置选定的值?

thi*_*zar 41 .net c# data-binding combobox winforms

我在c#windows窗体中使用了combobox.我将项目列表绑定如下:

var employmentStatus = new BindingList<KeyValuePair<string, string>>();

employmentStatus.Add(new KeyValuePair<string, string>("0", "[Select Status]"));
employmentStatus.Add(new KeyValuePair<string, string>("1", "Contract"));
employmentStatus.Add(new KeyValuePair<string, string>("2", "Part Time"));
employmentStatus.Add(new KeyValuePair<string, string>("3", "Permanent"));
employmentStatus.Add(new KeyValuePair<string, string>("4", "Probation"));

employmentStatus.Add(new KeyValuePair<string, string>("5", "Other"));
cmbEmployeeStatus.DataSource = employmentStatus;
cmbEmployeeStatus.ValueMember = "Key";
cmbEmployeeStatus.DisplayMember = "Value";
cmbEmployeeStatus.SelectedIndex = 0;
Run Code Online (Sandbox Code Playgroud)

我将所选值保存在数据库eg.1或2.现在我想从数据库项设置选定的值,如:

cmbEmployeeStatus.SelectedValue =employee.employmentstatus;     
Run Code Online (Sandbox Code Playgroud)

但是没有选择有价值的组合框.我怎样才能做到这一点?

sai*_*enz 47

试试这个吧.

cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.:)

  • 还要记住FindString,它返回以给定字符串开头的第一个元素,以及执行精确字符串匹配的FindStringExact. (9认同)

Cha*_*esW 15

为了手动设置数据库样式ComboBox,尝试设置数字(内部)和某些文本(可见)之间的关系,我发现你必须:

  1. 将项目存储在列表中(您已关闭 - 除了字符串,字符串 - 需要int,字符串)
  2. DataSource属性到列表(你很好)
  3. DataMember,DataValue(你很好)
  4. 加载默认值(你很好)
  5. 从数据库中提取价值(您的问题)
  6. 获得重新投入数据库的价值(下一个问题)

首先要做的事情.将KeyValuePair更改为如下所示:

(0,"选择")(1,"选项1")

现在,当你运行你的sql"从员工那里选择empstatus"并获得一个整数时,你需要设置组合框而不浪费一大堆时间.

简单地说:*** SelectedVALUE - 不是项目****

cmbEmployeeStatus.SelectedValue = 3;   //or

cmbEmployeeStatus.SelectedValue = intResultFromQuery;   
Run Code Online (Sandbox Code Playgroud)

无论您是否使用代码值手动加载了组合框,或者从查询中加载了comboBox,这都会有效.

如果你的外键是整数,(对于我所做的,它们都是),生活很容易.用户对comboBox进行更改后,您将在数据库中存储的值为SelectedValue.(根据需要转换为int.)

这是我将ComboBox设置为数据库中的值的代码:

if (t is DBInt) //Typical for ComboBox stuff
    {
    cb.SelectedValue = ((DBInt)t).value;
    }
Run Code Online (Sandbox Code Playgroud)

并检索:

((DBInt)t).value = (int) cb.SelectedValue;
Run Code Online (Sandbox Code Playgroud)

DBInt是Integer的包装器,但这是我的ORM的一部分,它让我手动控制数据绑定,并减少代码错误.

我为什么这么晚回答这个问题?我也在努力解决这个问题,因为网上似乎没有关于如何做到这一点的好消息.我想通了,并且认为我会很好并发布给其他人看.


小智 5

在 windows 应用程序中,我们像这样使用

 DDLChangeImpact.SelectedIndex = DDLChangeImpact.FindStringExact(ds.Tables[0].Rows[0]["tmchgimp"].ToString());
 DDLRequestType.SelectedIndex = DDLRequestType.FindStringExact(ds.Tables[0].Rows[0]["rmtype"].ToString());
Run Code Online (Sandbox Code Playgroud)