Windows 窗体
一组用于开发图形用户界面的 .NET Framework 托管库。
118 个问题
我仍然难以理解课堂上的调用方法。
假设我在 Form1 中有两个文本框,在 Form2 中有两个文本框,并且所有这四个文本框都使用相同的代码。
那么我怎样才能把代码放到类里,这样我就不需要重复代码了呢?我不明白的是:类没有文本框,我怎么能在那里写txtbox按键?
无论如何,如何编写它以及调用它的代码是什么?
谢谢。
private void txtBoxFirstNameinForm1_KeyPress(object sender, EventArgs e)
{
//Validate input character
}
private void txtBoxFirstNameinForm2_KeyPress(object sender, EventArgs e)
{
//Validate input character
}
private void txtBoxLastNameinForm1_KeyPress(object sender, EventArgs e)
{
//Validate input character
}
private void txtBoxLastNameinForm2_KeyPress(object sender, EventArgs e)
{
//Validate input character
}
Note:此问题总结整理于:How to call method from class?
>>类没有文本框,我怎么能写txtbox键 首先 ,您可以将 TextBox 从 ToolBox 拖到 Form1 和 Form2。(您可以在“视图”菜单中找到“工具箱”) 然后右键单击“文本框”,然后单击“属性”。 在“属性”页中,单击“事件”图标,然后找到 KeyPress 事件。 双击 KeyPress,您将在表单类代码中看到 txtbox 按键。 接下来,您可以将相同的代码(验证输入字符)放入方法中。 然后在 KeyPress 事件中调用此方法。 下面是一个简单的代码示例,您可以参考。
Form1.cs
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
validate();
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
validate();
}
public void validate()
{
//Validate input character
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.yourAction =validate;
f2.Show();
}
Form2.cs
public Form2()
{
InitializeComponent();
}
//Pass an action through to the new form
Form1 f1 = new Form1();
public Action yourAction { get; set; }
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
Action instance = yourAction;
if (instance != null)
instance();
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
Action instance = yourAction;
if (instance != null)
instance();
}
如果回复有帮助,请点击“接受答案”并点赞。
注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。