0
我在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;我++)*
是的,只有在兩種形式都可見的情況下,您的代碼纔有效,因爲您正在瀏覽開放式表單集合。如果你想在第二種形式中禁用它,你應該傳遞一些參數給其他形式的構造函數或類似的東西...... – Nino