如何在 Windows Form C# 的 TextBox 中显示文本

How to display text in a TextBox on a Windows Form C#

网上有几个关于这个问题的答案,但是 none 已经回答了我的问题。我有一个 Windows 表单,其中包含用户的详细信息列表,一些数据可以编辑,而另一些则不能。我想 'getUserName()'(其中 returns 一个用户名)并将其显示在文本框中

    // Display Student Details Form
    public void displayStudent()
    {
        StudentDetails sd = new StudentDetails();
        sd.ShowDialog();
    }

上面创建了包含多个标签和文本框的新表单,当它被创建(和显示)时,该表单上的文本框应该填充以包含学生信息(例如用户名、姓名、地址等)

    private void displayUserName_TextChanged(object sender, EventArgs e)
    {
        displayUserName.Text = displayUserName.Text = s.getUserName();
    }

s 是一个学生对象

上面的代码,我希望从学生对象中获取用户名并将其显示在文本框中以供其他用户查看并可能进行编辑。

试试displayUserName.Text = s.getUserName();

把它放在 Form Load 事件中,在 Button press 或 comboBox Selection 事件中...做一些假设(因为你没有提供很多细节),例如在后面的 StudentDetails Form 代码中:

public partial class StudentDetails : Form
{
    private int _studentId;

    private DbContext _context;

    public StudentDetails(int studentId)
    {
        _context = new DbContext();
        _studentId = studentId;
        InitializeComponent();
    }

    protected override void OnLoad(EventArgs e)
    {
        Student s = _context.Students.Find(_studentId);

        displayUserName.Text = s.getUserName();
        // Using a function here is overkill, perhaps.
        // This should also work here:
        // displayUserName.Text = s.FullName;


        base.OnLoad(e);
    }
} 

现在在您的主窗体中:

StudentDetails form = new StudentDetails(studentId);
form.ShowDialog() ;

顺便说一句,如果您至少不尝试然后展示您的尝试,大多数人不会费心回答您的问题。

试试这个代码,注意我确实指定 displayUserName 框的文本是在我创建对象之后给出的,而 x 只是你所拥有的任何东西,以确保实例具有要使用的数据集,而不是空白,这会继续错误。

// Display Student Details Form
public void displayStudent()
{
    StudentDetails sd = new StudentDetails();
    sd.getData(x);
    displayUserName.Text = sd.getUserName();
    sd.ShowDialog();
}

TextChanged 调用将是您在用户更改文本框的值后使用的调用,根据我的经验,它是处理表单而不是初始化表单的一部分.