2014-03-19 11 views
0

我在動態製作的面板上有一個單選按鈕和一個文本框。現在,我想在第二個單選按鈕被選中時禁用文本框,表示它們都已連接。我怎麼能爲它做這件事。我想讓這個活動有效。 非常感謝先進。 這是我的代碼是不工作:代碼中的動態事件

Panel pnl = new Panel(); 
pnl.Name = "pnl_"; 
pnl.Size = new Size(630, 80); 

RadioButton rd = new RadioButton(); 
rd.Name = "rd_" + dr[i]["Value_Name"].ToString(); 
rd.Text = dr[i]["Value_Name"].ToString(); 
rd.Location = new Point(i,i*2); 
pnl.Controls.Add(rd); 

TextBox txt = new TextBox(); 
txt.Name = "txt_" + Field_Name+"_"+dr[i]["Value_Name"].ToString(); 
txt.Size = new Size(171, 20); 
txt.Text = Field_Name + "_" + dr[i]["Value_Name"].ToString(); 
txt.Location = new Point(20, 30); 
pnl.Controls.Add(txt); 

////// ???? //////// 
rd.CheckedChanged += new EventHandler(eventTxt(txt)); 

void eventTxt(object sender,EventArgs e,TextBox txt) 
     { 
      RadioButton rd = (RadioButton)sender; 
      txt.Enabled = rd.Checked; 

     } 

回答

1

使用lambda關閉在相關變量(S):

rd.CheckedChanged += (s, args) => txt.Enabled = rd.Checked; 

如果你有一個比一個線的應用更,你可以調用一個方法來接受你關閉的任何參數,而不是將它全部內聯。

+0

非常感謝。這正是我正在尋找的。 – KOMAEI

0

我建議設置單選按鈕的Tag並得到走的依賴關係。

rd.Tag = txt; 

在事件處理程序使用此:

TextBox txt = (sender as Control).Tag as TextBox; 

txt.Enabled = ... 
0

您可以使用代碼中給出

rd.CheckedChanged += (s,argx) => txt.Enabled = rd.Checked; 
0

這裏是你如何能爲它創建一個事件:

//if you are using Microsoft Visual Studio, the following 
//line of code will go in a separate file called 'Form1.Design.cs' 
//instead of just 'Form1.cs' 
myTextBox.CheckChangedEventHandeler += new EventHandeler(checkBox1_CheckChanged); //set an event handeler 

public void checkBox1_CheckChanged(object sender, EventArgs e)  //what you want to happen every time the check is changed 
{ 
    if(checkBox1.checked == true) //replace 'checkBox1' with your check-box's name 
    {   

     myTextBox.enabled = false; //replace 'myTextbox' with your text box's name; 
             //change your text box's enabled property to false 
    } 
} 

希望它能幫助!