我在C#Winform的面板中有一堆文本框.每行文本框的命名如下:
tb1 tbNickName1 comboBox1
tb2 tbNickName2 comboBox2
tb3 tbNickName3 comboBox3
等等.
我在每行文本框旁边都有一个按钮.但是,不是让按钮指向每个按钮的不同事件,我想将按钮指向button1_Click事件并让它在那里完成所有处理.我知道如何做到这一点,我的所有按钮都指向button1_Click事件.
但我需要能够确定从哪个按钮调用(我能够做到),但我需要操作事件中文本框的名称,这样我就可以根据我在哪一行进行处理/我打电话给的按钮.
例如,如果我在tb2 tbNickName2 comboBox2文本框的第2行,那么我需要能够让button1_Click事件知道这一点,并自动将tb2 tbNickName2 comboBox2值分配给我在下面的示例中使用的tmp变量.
private void button1_Click(object sender, EventArgs e)
{
Button bt = (Button) sender; //will return 'button1'
string tmpEmail = null;
string tmpNickName = null;
string tmpGroup = null;
//I don't want to hard code the tb1.Text value here, I want to have
// the namechange based on which (Button) sender it was called from.
// For example button1 should assign all the
// tb1 tbNickName1 comboBox1 values
//If called from button2, then it should assign the
//tb2 tbNickName2 comboBox2 values instead
//How can I do this so tb1.Text is based off of the button # that I am
//calling for example tb(bt).Text would be cool but that does not work.
tmpEmail = tb1.Text; //What do I change tb1.Text to based on button #?
tmpNickName = tbNickName1.Text; //What do I change tbNickName1.Text to?
tmpGroup = comboBox1.Text;//What do I change comboBox1.Text to?
}
Run Code Online (Sandbox Code Playgroud)
我知道我没有很好地解释这一点,但这是我能做的最好的.
Button button = sender as Button;
string buttonIndex = button.Name.Substring(6);
string tempEmail = (this.Controls["tb" + buttonIndex] as TextBox).Text;
string tmpNickName = (this.Controls["tbNickName" + buttonIndex] as TextBox).Text;
string tmpGroup = (this.Controls["comboBox" + buttonIndex] as ComboBox).Text;
Run Code Online (Sandbox Code Playgroud)