2013-06-05 35 views
-2

我有一個2複選框和3個按鈕的窗體。當Button3被點擊時,程序檢查checkbox1是否被選中,如果被選中,文本框1的值變爲「Hello」。如果選中複選框2,則該值將變爲「請幫助」。如何使用複選框更改C#中TextBox的值?

using System; 
using System.Collections.Generic; 
using System.ComponentModel;  
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      textBox1.Text += "a"; 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      textBox1.Text += "b"; 
     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
     } 

     private void button3_Click(object sender, EventArgs e) 
     { 
      If (checkBox1.Checked = true) ; 
      { 
       textBox1.Text += ("hello "); 
      } 

      If(checkBox2.Checked = true); 
      { 
       textBox1.Text += ("hello "); 
      } 

      txtRun = new TextBox(); 
      txtRun.Name = "txtDynamic"; 
      txtRun.Location = new System.Drawing.Point(20, 18); 
      txtRun.Size = new System.Drawing.Size(200, 25); 
      // Add the textbox control to the form's control collection    
      this.Controls.Add(txtRun); 
     } 

     private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e) 
     { 
     } 
    } 
} 
+0

聽起來不錯,那麼問題是什麼?請根據[FAQ]具體說明。此外,您發佈的代碼不能編譯。這是問題嗎? – FishBasketGordo

回答

2

在所有的if語句行刪除;,並做如下

if (checkBox1.Checked) 
{ 
    textBox1.Text = "hello "; 
} 

if(checkBox2.Checked) 
{ 
    textBox1.Text = "please help"; 
} 

,如果你這樣做yourTextBox.Text +="something"將追加something當前文本框的文本。

如果您需要更換或完全改變文本框的文字,你可以做yourTextBox.Text ="something"(不+

而且具有動態控制,但無法找到它的

txtRun = new TextBox(); 

變化宣言這對

TextBox txtRun = new TextBox(); 
+0

編輯來修復'if'並刪除'= true',它會指定true並進入'if'塊。 – SimpleVar

+0

@YoryeNathan謝謝 – Damith

0

如果button3_Click處理器說法是錯誤的 它必須像

if (checkBox1.Checked == true) //or if (checkBox1.Checked) 
    { 
     textBox1.Text += ("Hello "); 
    } 

    if(checkBox2.Checked == true) //or if (checkBox2.Checked) 
    { 
     textBox1.Text += ("please help "); 
    } 

刪除「if」末尾的分號。

希望這會有所幫助。

0

我不知道爲什麼是這個問題,但是你在if語句中有一個問題,並且注意,在這種情況下你也有問題,程序只運行「;」一句話,如果,如果是真實的結果......除去;

 If (checkBox1.Checked == true) 
     { 
      textBox1.Text += ("hello "); 
     } 

     If(checkBox2.Checked == true) 
     { 
      textBox1.Text += ("hello "); 
     } 
0

當將Button3單擊該程序檢查下面的代碼將做到這一點

如果選擇checkbox1,如果它被選中文本框1的值更改爲「Hello」。如果選中複選框2,則該值將變爲「請幫助」。

private void button3_Click(object sender, EventArgs e) 
    { 
     if(checkBox1.Checked)textBox1.Text = ("Hello"); 
     if(checkBox2.Checked)textBox1.Text = ("Please Help"); 
    } 

出於某種原因,我有一種感覺,你的問題是不完整的,我只能回答正是你問什麼,如果有其他任何你所要完成的,請爲我提供更多的細節,我將很樂意延長我的回答。

另外,當您在原始代碼中動態創建該文本框時(我可能添加的內容在您的問題中根本沒有解決),它會不斷創建無限數量的下方的文本框,因爲每次點擊它在同一個地點創建另一個按鈕。

相關問題