2016-12-28 23 views
1

我需要當按下鼠標右鍵單擊創建一個文本框在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; 
     } 

    } 

我得到錯誤對象引用不設置到對象的實例。

+1

的可能的複製(HTTP ://tankoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – RandomStranger

+2

在'txt_KeyDown'事件中,'sender'是文本框,而不是按鈕。 所以這行'ss = sender作爲Button;'將'ss'設置爲null。 –

+0

你的意思是ss = null; ?? – Dim111

回答

1

一個解決這個問題的方法是在文本框的標籤屬性來保存對按鈕的引用:什麼是一個NullPointerException,以及如何解決呢]

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); 
    } 

} 
+0

它的作品謝謝你!但是,如何在輸入密鑰後關閉我的txt? – Dim111

+0

很高興提供幫助。我在'txt_KeyDown'事件處理程序的末尾添加了對'Controls.Remove(txt);'的調用。 –

相關問題