我需要當按下鼠標右鍵單擊創建一個文本框在midle的按鈕。 當按下輸入鍵在我的文本框中改變按鈕名稱爲文本框給定文本;更改按鈕名稱與動態文本框事件處理程序
這裏是我的代碼:
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;
}
}
我得到錯誤對象引用不設置到對象的實例。
的可能的複製(HTTP ://tankoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – RandomStranger
在'txt_KeyDown'事件中,'sender'是文本框,而不是按鈕。 所以這行'ss = sender作爲Button;'將'ss'設置爲null。 –
你的意思是ss = null; ?? – Dim111