Reputation: 49
I need when pressing Mouse Right click creating a textbox in midle of button. And when pressing enter key in my textbox to changing button name as textbox given Text;
Here is my code:
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;
}
}
I get error Object reference not set to an instance of an object.
Upvotes: 1
Views: 79
Reputation: 82524
One way to solve it is to hold a reference to the button in the Tag property of the textbox:
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);
}
}
Upvotes: 1