使用动态文本框事件处理程序更改按钮名称

时间:2016-12-28 09:33:12

标签: c#

按鼠标时我需要右键单击按钮中间创建一个文本框。 当按下文本框中的回车键以将文本框中的按钮名称更改为文本框时;

这是我的代码:

 TextBox txt;
 private void c_MouseDown(object sender, MouseEventArgs e)
    {
    if (e.Button == MouseButtons.Right)
        {
            ss = sender as Button;
            Point location = ss.Location;
            int xLocation = ss.Location.X;
            int yLocation = ss.Location.Y;

            txt = new TextBox();
            txt.Name = "textBox1";
            txt.Text = "Add Text";

            txt.Location = new Point(xLocation - 10, yLocation + 20);
            Controls.Add(txt);
            txt.Focus();
            txt.BringToFront();

            txt.KeyDown += txt_KeyDown;
        }
    }


    private void txt_KeyDown(object sender, KeyEventArgs e)
    {

        if (e.KeyCode == Keys.Enter)
        {
            ss = sender as Button;
            ss.Name = txt.Text;
        }

    }

我得到错误对象引用没有设置为对象的实例。

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是在文本框的Tag属性中保留对按钮的引用:

TextBox txt;
private void c_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
    {
        ss = sender as Button;
        Point location = ss.Location;
        int xLocation = ss.Location.X;
        int yLocation = ss.Location.Y;

        txt = new TextBox();
        txt.Name = "textBox1";
        txt.Text = "Add Text";
        txt.Tag = ss;

        txt.Location = new Point(xLocation - 10, yLocation + 20);
        Controls.Add(txt);
        txt.Focus();
        txt.BringToFront();

        txt.KeyDown += txt_KeyDown;
    }
}


private void txt_KeyDown(object sender, KeyEventArgs e)
{

    if (e.KeyCode == Keys.Enter)
    {
        ss = (sender as TextBox).Tag as Button;
        ss.Name = txt.Text;
        Controls.Remove(txt);
    }

}