如何从另一个表单中禁用多个文本框?
问题描述:
我在Form1中有这个组合框,当组合框值发生变化时,我需要禁用某些文本框,并且有一个按钮可以转到该窗体的文本框被禁用。如何从另一个表单中禁用多个文本框?
如何在不同时显示两种表单的情况下做我想做的事?
这里是代码:
public partial class Form1 : Form
{
internal Grading_Section grading;
internal TextBox te;
public Form1()
{
InitializeComponent();
grading = new Grading_Section();
grading.Show();
te = TxtAddress;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FindControl fc = new FindControl();
Grading_Section gr = new Grading_Section();
if (comboBox1.SelectedItem == "MSC")
{
((TextBox)fc.Ctrl(fc.TheForm("Grading_Section"), "textBox1")).Enabled = false;
((TextBox)fc.Ctrl(fc.TheForm("Grading_Section"), "textBox2")).Enabled = false;
((TextBox)fc.Ctrl(fc.TheForm("Grading_Section"), "textBox3")).Enabled = false;
}
else if (comboBox1.SelectedItem == "CSP")
{
((TextBox)fc.Ctrl(fc.TheForm("Grading_Section"), "textBox1")).Enabled = true;
((TextBox)fc.Ctrl(fc.TheForm("Grading_Section"), "textBox2")).Enabled = true;
((TextBox)fc.Ctrl(fc.TheForm("Grading_Section"), "textBox3")).Enabled = true;
}
}
private void BtnNext_Click(object sender, EventArgs e)
{
this.Visible = false;
Grading_Section g = new Grading_Section();
g.Show();
}
,这是我的FindControl类:
public class FindControl
{
Control c = null;
Control f = null;
public FindControl()
{
}
public Control TheForm(string name)
{
FormCollection fc = Application.OpenForms;
//---------------------------------------------------------------------------------
for (int i = 0; i < fc.Count; i++)
{
c = null;
if (fc[i].Name == name)
{
f = fc[i];
break;
}
}
return ((Control)f);
}
//---------------------------------------------------------------------------------
public Control Ctrl(Control f, string name)
{
* for (int i = 0; i < f.Controls.Count; i++)*
{
if (f.Controls[i].Name == name)
{
c = f.Controls[i];
break;
}
if (c == null)
{
if (f.Controls[i].Controls.Count > 0)
Ctrl(f.Controls[i], name);
}
if (c != null)
break;
}
return (c);
}
}
到目前为止,我发现这个代码,但它的工作原理是同时显示的形式的唯一途径否则会显示此错误:
当我删除此行时弹出错误:“grading.Show();
“NullReference例外是未处理的,类型的未处理的异常 'System.NullReferenceException' 发生在WindowsFormsApplication2.exe”
的误差从该行累积:
- 对(INT I = 0; i < f.Controls.Count;我++)*
答
private void BtnNext_Click(object sender, EventArgs e)
{
this.Visible = false;
Grading_Section g = new Grading_Section();
g.DisableTextBoxes(comboboxValue);
g.Show();
}
在形式Garding_Section,你应该创建一个方法是这样的:
public void DisableTextBoxes(string value)
{
if(value == "a")
{
//disabele related texboxes
}
else if(value == "b")
{
//disable related textboxes.
}
}
我希望这有助于。
是的,只有在两种形式都可见的情况下,您的代码才有效,因为您正在浏览开放式表单集合。如果你想在第二种形式中禁用它,你应该传递一些参数给其他形式的构造函数或类似的东西...... – Nino