我是否应该使用Winforms组合框';是SelectedItem、SelectedText还是SelectedValue?
我想将组合框中的值作为参数传递给SQL语句。Winforms组合框为我提供了几个检索值的选项,即SelectedItem、SelectedText和SelectedValue。在这种情况下,使用哪种方法最好/最安全我是否应该使用Winforms组合框';是SelectedItem、SelectedText还是SelectedValue?,winforms,combobox,selecteditem,selectedvalue,selectedtext,Winforms,Combobox,Selecteditem,Selectedvalue,Selectedtext,我想将组合框中的值作为参数传递给SQL语句。Winforms组合框为我提供了几个检索值的选项,即SelectedItem、SelectedText和SelectedValue。在这种情况下,使用哪种方法最好/最安全 if (comboBox1.DropDownStyle == DropDownStyle.DropDown || comboBox1.DropDownStyle == DropDownStyle.Simple) { return comboBox1.Text; }
if (comboBox1.DropDownStyle == DropDownStyle.DropDown ||
comboBox1.DropDownStyle == DropDownStyle.Simple)
{
return comboBox1.Text;
}
Text
可能是最好的使用方法。这将从组合框中获取当前选定的文本作为字符串
if (comboBox1.DropDownStyle == DropDownStyle.DropDownList)
{
return comboBox1.GetItemText(comboBox1.SelectedItem);
}
对于此样式,您无法从组合框中获取文本。这将返回当前
SelectedIndex中项目的字符串。SelectedValue可能是最好的使用方法
SelectedText将为您提供可编辑部分的选定文本,selected Item将返回对象,selected index将返回索引。通常,对于所选的应用程序,提取并使用值。
退房
SelectedItem似乎是一个安全的选择
我有这个密码:
NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedValue.ToString();
…与NRE一起坠毁
将其更改为此后:
NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedItem.ToString();
…它工作正常。这取决于三件事1模式2下拉式3所需值
在ComboBox上。SelectedIndex已更改
- 未绑定模式
a。DropDownStyle=下拉菜单
- SelectedItem将返回=SelectedText
- SelectedValue将返回=“”
- SelectedText将返回=SelectedText
b。DropDownStyle=DropDownList
- SelectedItem将返回=SelectedText
- SelectedValue将返回=“”
- SelectedText将返回=“”
- 使用数据绑定模式(表示您正在从某些数据源(如SQL Server表)填充组合框)
您将选择表中的一列作为DisplayMember,并选择同一列或另一列作为ValueMember
a。DropDownStyle=下拉菜单
- SelectedItem将返回=System.Data.DataRowView(提示)
- SelectedValue将返回=ValueMemeber的值
- SelectedText将返回=SelectedText(DisplayMember的值)
b。DropDownStyle=DropDownList
- .SelectedItem将返回=System.Data.DataRowView(提示)
- .SelectedValue将返回=ValueMember的值
- .SelectedText将返回=“”
注意:您还可以使用.Text返回组合框的文本
结论:
解除绑定模式
- .SelectedItem是最佳选择
数据绑定模式
a。ValueMember是必需的
- .SelectedValue是最佳选择
b。DisplayMember是必需的
- .文本是最好的选择
DropDownStyle属性的值是多少?我终于开始测试它了;当我尝试SelectedValue时,它爆炸了。SelectedItem可以工作,但是://String Center=comboxcenters.SelectedValue.ToString();谢谢你的详细解释。这真的很有帮助。
NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedItem.ToString();