如何获取发件人的按钮名称。

问题描述:

你好朋友

抱歉我的英语不好。

这是我的问题:

i有一个表格。我动态创建5个按钮表格。(在flowLayoutPanel1中)

i想要当我点击每个按钮时它的文字或名字出现在label1上。

i想通过发送者按钮来做。

这是我的代码:(它不起作用)

hello friends
sorry for my poor English.
this is my question :
i have a form .i create dynamically 5 buttons into the form.(in the flowLayoutPanel1)
i want when i click every button it''s text or name be appeared on a label1.
i want to do by sender button.
this is my code: (it do not work)

public void addbutton_dynam_Click(object sender, EventArgs e)
{
    counter += 1;
    Button btnAdd = new Button();
    this.Text = counter.ToString();
    btnAdd.Name = "click";
    btnAdd.BackColor = Color.Gray;
    btnAdd.Text = "Add";
    btnAdd.Location = new System.Drawing.Point(20, 20);

    flowLayoutPanel1.Controls.Add(btnAdd);

}



代码用于点击...


code is for when i click ...

public void click(object sender)
{
    Button btn = (Button)sender;
    this.label1.Text = (btn.Name + " pressed");

}



请帮助。


pls help.

您需要添加一个点击按钮的事件处理程序 - 或者不调用事件处理程序方法。

You need to add a click event handler to the button - or the event handler method is not called.
    Button btnAdd = new Button();
    this.Text = counter.ToString();
    btnAdd.Name = "click";
    btnAdd.Click += new EventHandler(btnAdd_Click);
    btnAdd.BackColor = Color.Gray;
    btnAdd.Text = "Add";
    btnAdd.Location = new System.Drawing.Point(20, 20);

    flowLayoutPanel1.Controls.Add(btnAdd);
    }

void btnAdd_Click(object sender, EventArgs e)
    {
    Button btn = (Button)sender;
    if (btn != null)
        {
        label1.Text = (btn.Name + " pressed");
        }
    }

请注意在处理程序中检查 null - 值得一直添加这个。您可以使用相同的方法与各种控件,并检查停止它抛出空引用异常。

Note the check for null in the handler - it''s worth always adding this. You can use the same method with a variety of controls and checking stops it throwing a null reference exception.