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

B. *_*non 10 combobox selectedvalue selecteditem selectedtext winforms

我想将组合框中的值作为参数传递给SQL语句.Winforms组合框为我提供了几个检索值的选项,即SelectedItem,SelectedText和SelectedValue.在这种情况下哪一个最好/最安全?

Aar*_*ing 9

if (comboBox1.DropDownStyle == DropDownStyle.DropDown || 
    comboBox1.DropDownStyle == DropDownStyle.Simple)
{
    return comboBox1.Text;
}
Run Code Online (Sandbox Code Playgroud)

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

if (comboBox1.DropDownStyle == DropDownStyle.DropDownList)
{
    return comboBox1.GetItemText(comboBox1.SelectedItem);
}
Run Code Online (Sandbox Code Playgroud)

对于这种风格,你无法从中获取文本ComboBox.这将返回当前项目中的字符串SelectedIndex.


Hab*_*bib 7

SelectedValue可能是最好的一个使用
SelectedText将为您提供可编辑部分的选定文本,Selected Item将返回您对象并且所选索引将返回您的索引.通常对于应用程序,提取并使用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.)
Run Code Online (Sandbox Code Playgroud)


Muh*_*oon 7

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

在ComboBox.SelectedIndexChanged上

  • 未绑定模式

    一个.DropDownStyle = DropDown

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

      湾 DropDownStyle = DropDownList

      • SelectedItem将返回= SelectedText
      • SelectedValue将返回=""
      • SelectedText将返回=""
  • 使用数据绑定模式(表示您从某些数据源(即SQL Server表)填充ComboBox)您将选择表的列作为DisplayMember,并选择与ValueMember相同或相同的列.

    一个.DropDownStyle = DropDown

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

      湾 DropDownStyle = DropDownList

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

注意:您还可以使用返回= ComboBox文本的.Text

结论:

  1. Unboud模式

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

    一个.ValueMember是必需的

    • .SelectedValue是最好的选择

      湾 DisplayMember是必需的

      • .Text是最好的选择