我是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);
}
}
答案 0 :(得分:1)
所以这段代码对我来说很好:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 2;
}
如果没有要访问的项目,则无法访问ItemSource。简单的方法是在Desinger上启动项目
(非本地化IDE的Sory)比您可以将Property SelectedIndex设置为退出的索引。另一种方法是使用Combobox1.Items.Add
功能添加所有HDMI项目。
如果您曾在VB中使用过表格,那么它仍然是相同的
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;
}