1

我是 C# 的新手,下面的代码似乎没有选择我的组合框值:

private void button1_Click(object sender, EventArgs e)
{

   cbPortNumber.SelectedValue = 3;

或者

   cbPortNumber.setValue("3");

或者

   cbPortNumber.SelectedIndex = cbPortNumber.FindString("3");

或者

   cbPortNumber.SelectedIndex = cbPortNumber.Items.IndexOf(cbPortNumber.Items.FindByValue("HDMI 4"));

}

下拉列表如下所示: 在此处输入图像描述

上面的所有代码似乎都没有在列表中选择 HDMI 4 ...我没有任何错误,但我也没有选择它。

任何帮助都会很棒!

更新显示组合框 在此处输入图像描述

更新 2

    // 
    // cbPortNumber
    // 
    this.cbPortNumber.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
    this.cbPortNumber.Enabled = false;
    this.cbPortNumber.FormattingEnabled = true;
    this.cbPortNumber.Location = new System.Drawing.Point(174, 40);
    this.cbPortNumber.Name = "cbPortNumber";
    this.cbPortNumber.Size = new System.Drawing.Size(133, 21);
    this.cbPortNumber.TabIndex = 11;
    this.cbPortNumber.Text = "global_hdmi_port";
    this.helpPortNumber.SetToolTip(this.cbPortNumber, "The HDMI port number, to which you connected your USB-CEC adapter.");
    this.cbPortNumber.SelectedIndexChanged += new System.EventHandler(this.cbPortNumber_SelectedIndexChanged);

#region Global settings
public CECSettingByte HDMIPort
{
  get
  {
    if (!_settings.ContainsKey(KeyHDMIPort))
    {
      CECSettingByte setting = new CECSettingByte(KeyHDMIPort, "HDMI port", 1, _changedHandler) { LowerLimit = 1, UpperLimit = 15, EnableSetting = EnableHDMIPortSetting };
      setting.Format += delegate(object sender, ListControlConvertEventArgs args)
      {
        ushort tmp;
        if (ushort.TryParse((string)args.Value, out tmp))
          args.Value = "HDMI " + args.Value;
      };

      Load(setting);
      _settings[KeyHDMIPort] = setting;
    }
    return _settings[KeyHDMIPort].AsSettingByte;
  }
}

更新 3

这就是在该下拉列表中选择某些内容后触发操作的原因:

private void OnSettingChanged(CECSetting setting, object oldValue, object newValue)
{
  if (setting.KeyName == CECSettings.KeyHDMIPort)
  {
    CECSettingByte byteSetting = setting as CECSettingByte;
    if (byteSetting != null)
    {
      if (!Settings.OverridePhysicalAddress.Value)
        Config.HDMIPort = byteSetting.Value;
      CECActions.SetConnectedDevice(Settings.ConnectedDevice.Value, byteSetting.Value);
    }
  }
4

1 回答 1

1

所以这段代码对我来说很好用:

private void button1_Click(object sender, EventArgs e)
{
    comboBox1.SelectedIndex = 2;
}

如果没有要访问的项目,您将无法访问 ItemSource。简单的方法是在 Desinger 上初始化项目

在此处输入图像描述

(对于非本地化的 IDE 抱歉)您可以将 Property SelectedIndex 设置为退出的索引。另一种方法是添加所有具有该Combobox1.Items.Add功能的 HDMI 项目。

如果您曾经在 VB 中使用过 Forms ......它仍然是一样的

public Form1()
{
    InitializeComponent();

    var hdmi = "HDMI";

    for (int i = 1; i < 15; i++)
    {
        comboBox1.Items.Add( hdmi + i);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    if (comboBox1.Items.Count >= 2)
        comboBox1.SelectedIndex = 2;
}
于 2013-05-11T00:46:10.007 回答