【问题标题】:How do I get the information typed into a TextBox?如何获取输入到 TextBox 中的信息?
【发布时间】:2020-01-14 22:38:21
【问题描述】:

我想在以后的部分中利用输入到 TextBox 中的信息 这个程序。该程序将其全部设置在一个表格中,当我键入时 在文本框中输入一些内容并按 Enter 键,它转到第 32 行, Console.WriteLine,正确并显示引用的部分“进行计算 这里”,但不是在 TextBox 中键入的值 txtFolder。

using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;

public class MainForm : Form {

  private TextBox txtFolder;

  // set up the window
  public MainForm() {
    InitializeComponents();
  }

  private void InitializeComponents() {
    this.Text = "Textbox";
    Width = 500;

    // get textbox entry
    Label sbfldr           = new Label();
    sbfldr.Location        = new Point(10,140);
    sbfldr.Size            = new Size (315,20);
    sbfldr.Text = "Enter something into textbox and press the ENTER key";
    this.Controls.Add(sbfldr);
    TextBox txtFolder      = new TextBox();
    txtFolder.Location     = new Point(325,139);
    txtFolder.KeyUp += getFolder;
    txtFolder.Parent = this;
    this.Controls.Add(txtFolder);
  }

  private void getFolder(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.Enter) {
      Console.WriteLine("do calculations here "+txtFolder);
      e.Handled = true;
    }
  }

  public class Program {
    public static void Main(string[] args) {
      Application.Run( new MainForm() );
    }
  }
}

【问题讨论】:

  • txtFolder.Text :)

标签: c# forms textbox enter


【解决方案1】:

您可以使用Text 属性获取TextBox 的值:

string myValue = myTextBox.Text;

在你的代码中,你会这样:

Console.WriteLine("do calculations here " + txtFolder.Text);

Here is the documentation for TextBox.Text

【讨论】:

    【解决方案2】:

    改变这个:

    Console.WriteLine("do calculations here "+txtFolder);
    

    到这里:

    Console.WriteLine("do calculations here "+txtFolder.Text);
    

    【讨论】:

    • 抱歉,这些答案不起作用。编译后,我收到消息“TextBox.cs(7,23): warning CS0649: Field 'Mainform.txtFolder' is never assigned, and will always have its default value null
    • 听起来像是一个无关的问题。听起来您从未创建文本框控件并将其分配给txtFolder. 通常这是在InitializeComponent 中完成的。您可能希望使用表单设计器删除控件并再次添加它。
    • 谢谢。我通过将“private”实例更改为“public”解决了与 oop 相关的问题
    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    相关资源
    最近更新 更多