作者a0960330 (ViperLiu)
看板C_Sharp
标题[问题] 点击button去改变textbox的文字内容
时间Mon Jan 19 10:57:00 2015
我现在试着写一个计算机程式
可是我在训练自己用程式码设计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://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1421636222.A.737.html
1F:推 GoalBased: 有完整一点的程式码吗 01/19 11:00
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
2F:推 wheattea: TextBox result 不要写在Form1()里 Btn_click找不到的 01/19 11:56
不然应该写在哪里?想把他写在外面当全域变数好像也不行......大大给个指点吧
※ 编辑: a0960330 (220.130.225.223), 01/19/2015 12:10:37
4F:→ CiC: 看错了XD 你有绑了。那Click方法可以取出sender转型TextBox 01/19 12:55
5F:推 soup514: controls.find 01/19 12:59
6F:推 CrazyAngel: 如果你控制项用拉的,可以发现designer也是将控制项 01/19 16:14
7F:→ CrazyAngel: 宣告在最外层 01/19 16:15
谢谢大家,问题解决了!
※ 编辑: a0960330 (36.224.71.227), 01/20/2015 21:35:28