2012-09-17 77 views
-1

我在TextChanged事件處理程序中獲取文本框的Text值時遇到問題。無法從TextChanged事件處理程序中引用文本框的文本

我有以下代碼。 (簡體)

public float varfloat; 

private void CreateForm() 
{ 
    TextBox textbox1 = new TextBox(); 
     textbox1.Location = new Point(67, 17); 
     textbox1.Text = "12.75"; 
     textbox1.TextChanged +=new EventHandler(textbox1_TextChanged); 
} 

private void textbox1_TextChanged(object sender, EventArgs e) 
    { 
     varfloat = float.Parse(textbox1.Text); 
    } 

我得到以下錯誤:'名稱textbox1在當前上下文中不存在'。

我可能在某個地方犯了一個愚蠢的錯誤,但我是C#的新手,希望得到一些幫助。

在此先感謝!

回答

2

您已經聲明textBox1局部變量CreateForm。該變量只存在於該方法內。

三個簡單的選擇:

  • 使用lambda表達式中CreateForm創建事件處理程序

    private void CreateForm() 
    { 
        TextBox textbox1 = new TextBox(); 
        textbox1.Location = new Point(67, 17); 
        textbox1.Text = "12.75"; 
        textbox1.TextChanged += 
         (sender, args) => varfloat = float.Parse(textbox1.Text); 
    } 
    
  • 鑄造senderControl並使用它:

    private void textbox1_TextChanged(object sender, EventArgs e) 
    { 
        Control senderControl = (Control) sender; 
        varfloat = float.Parse(senderControl.Text); 
    } 
    
  • textbox1更改爲實例變量。如果你想在你的代碼的其他任何地方使用它,這將會很有意義。

哦,請不要使用公共字段:)

0

定義textbox1在類級作用域而不是函數作用域的外側CreateForm(),以便它可用於textbox1_TextChanged事件。

TextBox textbox1 = new TextBox(); 

private void CreateForm() 
{  
     textbox1.Location = new Point(67, 17); 
     textbox1.Text = "12.75"; 
     textbox1.TextChanged +=new EventHandler(textbox1_TextChanged); 
} 

private void textbox1_TextChanged(object sender, EventArgs e) 
{ 
    varfloat = float.Parse(textbox1.Text); 
} 
+0

很好的建議做了,謝謝。 –

+0

不客氣。 – Adil

1

試試這個:

private void textbox1_TextChanged(object sender, EventArgs e) 
{ 
    varfloat = float.Parse((sender as TextBox).Text); 
} 
+0

你知道'sender'參數將會是一個文本框,所以你應該只說'(TextBox)sender'。 – siride

+0

@siride,兩者都是一樣的我不這麼認爲它的行爲有所不同 –

+0

它們實際上並不相同,因爲它執行類型檢查,然後執行類型轉換,而我只執行類型轉換。如果結果是發件人不是TextBox的情況下,你的方法將拋出一個空引用異常,並且我會拋出適當的類型轉換異常。最後,我的方法恰當地記錄了意圖和期望。 – siride

0

您沒有添加文本框控件到窗體。

它可以作爲

TextBox txt = new TextBox(); 
txt.ID = "textBox1"; 
txt.Text = "helloo"; 
form1.Controls.Add(txt); 
+0

For more info http://stackoverflow.com/questions/4665472/using-dynamically-created-controls-in-c-sharp – Pushpendra

+0

這當然是原始代碼中的一個問題,但這不是OP問的問題關於。 – siride

+0

如果控件是動態創建的,則必須將其添加到表單中,否則它將無法訪問。 糾正我,如果我錯了。 – Pushpendra

相關問題