[問題] 點擊button去改變textbox的文字內容

看板C_Sharp作者 (ViperLiu)時間9年前 (2015/01/19 10:57), 9年前編輯推噓4(403)
留言7則, 5人參與, 最新討論串1/1
我現在試著寫一個計算機程式 可是我在訓練自己用程式碼設計GUI 因此,所有的button都是用Controls.Add()加上去的 public Form1() { InitializeComponent(); } 我把Controls.Add()都寫在這個裡面 其中有: TextBox result = new TextBox(); Controls.Add(result); 可是在處理按鈕事件的時候 我不能直接讓result.text="1" 他說result是區域變數 也就是說 在 private void btn1_Click(object sender, EventArgs e) { } 在這個區塊裡面,沒有result.text這個東西 請問一下,是我加入控制項的方法有錯嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.130.225.223 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1421636222.A.737.html

01/19 11:00, , 1F
有完整一點的程式碼嗎
01/19 11:00, 1F
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Button btn1 = new Button(); btn1.Text = "1"; btn1.SetBounds(30, 170, 30, 30); Controls.Add(btn1); TextBox result = new TextBox(); Controls.Add(result); btn1.Click += new System.EventHandler(btn1_Click); } private void Form1_Load(object sender, EventArgs e) { } private void btn1_Click(object sender, EventArgs e) { result.text="1";//找不到result } } } 已補上,拜託大家了 ※ 編輯: a0960330 (220.130.225.223), 01/19/2015 11:14:50

01/19 11:56, , 2F
TextBox result 不要寫在Form1()裡 Btn_click找不到的
01/19 11:56, 2F
不然應該寫在哪裏?想把他寫在外面當全域變數好像也不行......大大給個指點吧 ※ 編輯: a0960330 (220.130.225.223), 01/19/2015 12:10:37

01/19 12:54, , 3F
http://goo.gl/qJMe0j new按鈕的時候順便綁定Click事件
01/19 12:54, 3F

01/19 12:55, , 4F
看錯了XD 你有綁了。那Click方法可以取出sender轉型TextBox
01/19 12:55, 4F

01/19 12:59, , 5F
controls.find
01/19 12:59, 5F

01/19 16:14, , 6F
如果你控制項用拉的,可以發現designer也是將控制項
01/19 16:14, 6F

01/19 16:15, , 7F
宣告在最外層
01/19 16:15, 7F
謝謝大家,問題解決了! ※ 編輯: a0960330 (36.224.71.227), 01/20/2015 21:35:28
文章代碼(AID): #1Kl79-St (C_Sharp)