c# - 单击按钮后如何创建新的文本框?

标签 c# button

我想编写一个程序,在单击 Button3 后创建一个新的 TextBox。 出于某种原因,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);
      }

        }



        }
    }
}

最佳答案

您需要在 C# 中声明一个变量,然后才能使用它。

使用任一个

TextBox txtRun = new TextBox();

或使用implicitly typed变量:

var txtRun = new TextBox();

关于c# - 单击按钮后如何创建新的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930505/

相关文章:

c# - 集合中集合的 Where 子句

c# - 来自程序集的 WPF 自定义 FontFamily?

Javascript onclick 不适用于移动设备

javascript - HTML - 用视频替换 div(图像和按钮)(仅当我按下按钮时)

javascript - 页面上的任何按钮都会发送表单,即使是表单标签之外的按钮

c# - Web 服务中的 WCF 服务主机

c# - 如何让基类调用它的虚函数?

javascript - Windows Phone 上的后退按钮(HTML 应用程序)

java - 如何: Organize Buttons and stuff with JavaFX

c# - Windows 服务无法获得正确的系统文化