C# 代码中的动态事件
我有一个单选按钮和一个动态制作的面板上的文本框。现在,我想在选中第二个单选按钮时禁用文本框,这意味着它们都已连接。我怎样才能为它举办活动。我想让这项活动开展起来。 非常感谢你的帮助。 这是我不工作的代码:C# 代码中的动态事件,c#,C#,我有一个单选按钮和一个动态制作的面板上的文本框。现在,我想在选中第二个单选按钮时禁用文本框,这意味着它们都已连接。我怎样才能为它举办活动。我想让这项活动开展起来。 非常感谢你的帮助。 这是我不工作的代码: Panel pnl = new Panel(); pnl.Name = "pnl_"; pnl.Size = new Size(630, 80); RadioButton rd = new RadioButton(); rd.Name = "rd_" + dr[i]["Value_Name"
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;
}
我建议设置单选按钮的
标签
,并查看依赖项
rd.Tag = txt;
在事件处理程序中,请使用以下命令:
TextBox txt = (sender as Control).Tag as TextBox;
txt.Enabled = ...
使用lambda关闭相关变量: 如果您有多个单行实现,您可以调用一个方法来接受您关闭的任何参数,而不是将其全部包含在内联中。您可以使用给定的代码
rd.CheckedChanged += (s,argx) => txt.Enabled = rd.Checked;
以下是如何为其创建事件:
//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
}
}
希望有帮助 非常感谢。这正是我要找的。
//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
}
}