我想寫一個程序,它將創建一個新的TextBox,一旦Button3被點擊。 由於某些原因,C#不能識別txtRun。它表示名稱txtRun在當前上下文中不存在。這裏是我的代碼:單擊按鈕後如何創建新的文本框?
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)
{
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);
}
}
}
}
}
您還需要給每個新的TextBox一個不同的**位置()**,否則每次單擊button3時新的TextBox就會坐在上一個(s)頂部,並且最終會出現一個大疊加。 –
我建議使用諸如FlowLayoutPanel或TableLayoutPanel之類的東西來分配一個不同的位置,因爲它可能變得非常麻煩並且浪費時間,特別是如果你只是想要格式化的網格。 – CodeCamper