我应该使用Winforms组合框的SelectedItem、SelectedText还是SelectedValue?

12
在这种情况下,我可以使用Winforms组合框中的SelectedItem属性作为参数传递到SQL语句中。但是请注意,您需要确保值转换为正确的数据类型,并对输入进行适当的验证和过滤,以防止SQL注入攻击等安全问题。

DropDownStyle 属性的值是什么? - Aaron Deming
5个回答

9
if (comboBox1.DropDownStyle == DropDownStyle.DropDown || 
    comboBox1.DropDownStyle == DropDownStyle.Simple)
{
    return comboBox1.Text;
}

Text 可能是最好的选择。它将当前选定的文本从 ComboBox 中作为字符串获取。

if (comboBox1.DropDownStyle == DropDownStyle.DropDownList)
{
    return comboBox1.GetItemText(comboBox1.SelectedItem);
}

对于这种样式,你不能从ComboBox中获取文本。它会返回当前SelectedIndex所在项目的字符串。


9

SelectedValue(已选择的值)可能是最好的选择。
SelectedText(已选择文本)将为您提供可编辑部分的选定文本,Selected Item(已选择项)将返回对象,而selected index(已选择索引)将返回索引。通常情况下,应用程序会提取并使用SelectedValue。请查看MSDN上的ComboBox

SelectedIndex   Gets or sets the index specifying the currently selected item.                (Overrides ListControl.SelectedIndex.)
SelectedItem    Gets or sets currently selected item in the ComboBox.
SelectedText    Gets or sets the text that is selected in the editable portion of a ComboBox.
SelectedValue   Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)

1
我终于开始测试了,当我尝试使用SelectedValue时,它失败了。不过SelectedItem可以正常工作://String Center = comboBoxCenters.SelectedValue.ToString(); <- 出现有关对象未实例化的错误消息(是的,在我逐步执行时它为null) String Center = comboBoxCenters.SelectedItem.ToString(); // <- 这个可以正常工作 - B. Clay Shannon-B. Crow Raven

9

这取决于三件事:1. 模式 2. DropDownStyle 3. 必需值

在 ComboBox.SelectedIndexChanged 事件中

  • 未绑定的 模式

    a. DropDownStyle = DropDown

    • SelectedItem 将返回 = SelectedText
    • SelectedValue 将返回 = ""
    • SelectedText 将返回 = SelectedText

      b. DropDownStyle = DropDownList

      • SelectedItem 将返回 = SelectedText
      • SelectedValue 将返回 = ""
      • SelectedText 将返回 = ""
  • 使用数据绑定的 模式(意味着您从某个数据源,如 SQL Server 表中填充 ComboBox)。

    a. DropDownStyle = DropDown

    • SelectedItem 将返回 = System.Data.DataRowView(提示)
    • SelectedValue 将返回 = ValueMember 的值
    • SelectedText 将返回 = SelectedText(DisplayMember 的值)

      b. DropDownStyle = DropDownList

      • SelectedItem 将返回 = System.Data.DataRowView(提示)
      • SelectedValue 将返回 = ValueMember 的值
      • SelectedText 将返回 = ""

注意:您也可以使用 .Text,它将返回 ComboBox 的文本

结论:

  1. 未绑定的模式

    • .SelectedItem 是最佳选择
  2. 数据绑定的模式

    a. 必须使用 ValueMember

    • .SelectedValue 是最佳选择

      b. 必须使用 DisplayMember

      • .Text 是最佳选择

感谢您详细的解释。这真的很有帮助。 - Rahul Techie

2

微软建议使用此选项作为值。

ComboBox1.SelectedItem.ToString()

0

SelectedItem 似乎是一个安全的选择。

我有这段代码:

NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedValue.ToString();

...由于 NRE 崩溃。

将其更改为以下内容后:

NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedItem.ToString();

...它正常运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接