【发布时间】:2012-01-30 17:09:38
【问题描述】:
好的,所以我有 form1 和 form2。 Form1 有一个 form2 需要访问的组合框。在 form2 上,我创建了一个继承 form1 的新类。像这样。
public partial class form2 : Form
{
public form2()
{
InitializeComponent();
//from here I create tasks that reference the code in the newClass class
}
}
public class newClass : projectname.form1
{
public newClass()
{
//methods I access from from the above code
}
}
我没有遇到任何跨线程问题,但由于某种原因,每次我尝试从该组合框中获取任何类型的值时,它总是为 null 或空字符串。我试过了:
If (combobox.selecteditem == @"C:\")
{
//do something
}
还有:
If (combobox.text == @"C:\")
{
//do something
}
还有:
If (combobox.selectedindex == combobox.items.indexof(@"C:\")
{
//do something
}
还有:
If (combobox.selecteditem == combobox.findstringexact(@"C:\")
{
//do something
}
通常,我只会使用:(在我的情况下,出于某种原因,它是 -1)
If (combobox.selectedindex == -1)
{
//do something
}
这很好用,但是组合框中的项目并不总是相同的,所以你明白为什么这不是一个准确的方法。我一直在阅读无数的帖子,似乎
combobox.selecteditem
考虑到我使用的是 DropDownList 类型的组合框,这是我的最佳选择。当我使用它时没有任何反应,除了它给我一个警告,将(字符串)放在“=”符号的左侧。像这样:
If (combobox.selecteditem == @"C:\")
{
//gives warning that I need (string) on left side of '='
}
如果我这样做,没有警告,但仍然没有。
If ((string)combobox.selecteditem == @"C:\")
{
//do something
}
组合框正在 form1_load 上填充:
string[] combobox = Directory.GetLogicalDrives();
foreach (string box5 in combobox)
{
combobox.Items.Add(box5);
}
我正在使用 C#、Windows 窗体应用程序、.Net Framework 4.0
如果有人能对此有所了解,将不胜感激。我正在把头发拉出来。 :)
【问题讨论】:
-
public class form1 : form1.form2- 什么? Form1 不必与 form2 相关,它只需要对 form2 的引用,以便它可以访问组合框。 -
public class form1 : form1.form2是什么意思?form1如何继承form1.form2? “在form2上我创建了一个继承form1的新类”是什么意思。您如何“在表单上”创建课程?您显示的代码是form1或form2的一部分吗?combobox位于什么表格上?对不起,我完全不明白你在这里要做什么。 -
对不起。我实际上搞砸了第一部分。我将编辑我的问题以反映。
标签: c# winforms c#-4.0 combobox selecteditem