winforms C#依名称取得ComboBox中的SelectedIndex

vlf7wbxs  于 2022-11-16  发布在  C#
关注(0)|答案(2)|浏览(168)

我必须按名称处理一些控件

this.Controls.Find(String.Format("lbl{0}", index),
            true)[0].Text = data[i].ToString();

但当我尝试按名称获取组合框时,它无法显示SelectedIndex属性

this.Controls.Find(String.Format("cmbDat{0}", index), true)[0].

我能帮谁?

e0uiprwp

e0uiprwp1#

您必须将它转换为ComboBox,因为Find()会传回Control,而Control不包含SelectedIndex属性。
请尝试以下操作:

ComboBox theComboBox = this.Controls.Find(String.Format("cmbDat{0}", index), true) as ComboBox;

// Verify the combo box was found before trying to use it
if(theComboBox != null)
{
    // Do whatever you want with the combo box here
    theComboBox.SelectedIndex = ???
    theComboBox.Text = ???
}
jqjz2hbq

jqjz2hbq2#

这种方式看起来更容易https://stackoverflow.com/a/1639106/12537158,你所需要的只是这一行:

Control ctn = this.Controls[name];

相关问题