我有一个表单,我可以从一个窗口输入数据,然后按Enter键(btnEnter)并单击display(btnShowBooks)按钮并在其他窗口中显示数据。当我按下下面的代码按btnEnter然后单击btnShowBooks以在新窗口中显示输入时,txtBookList文本框仍为空。这是一个简化的代码,不起作用,希望得到一些提示。
BookEntry表单文件
private void btnEnter_Click(object sender, EventArgs e)
{
BookList bookList = new BookList();
bookList.txtBookList.Text = "aaa";
}
BookList表单文件,其中我有布局和关闭按钮,因此没有任何相关代码。只有texbox名为txtBookList和btnClose按钮。
在BookList设计器文件中,我将该字段公开:
public System.Windows.Forms.TextBox txtBookList;
的问候。 HelpNeeder。
- 已解决 -
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;
using System.Collections;
namespace Lab_8
{
public partial class BookEntry : Form
{
BookList bookList = new BookList();
public BookEntry()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
bookList.txtBookList.Text = "aaa";
}
private void btnShowBooks_Click(object sender, EventArgs e)
{
bookList.ShowDialog();
}
}
}
答案 0 :(得分:2)
我刚刚复制了这个并且工作正常(VS2010 .NET4)..你之后是否展示了相同的表单实例? (如下所示):
BookList bookList = new BookList();
bookList.txtBookList.Text = "aaa";
bookList.Show();
修改强>
鉴于您的回答,您似乎在实例化单独的表单。以下是您需要做的事情:
首先,在您的主要表单中,声明:
private BookList _bookList = new BookList();
然后,只要您需要引用该表单,请使用_bookList来完成该操作。 E.g:
_bookList.txtBookList.Text = "aaa";
_bookList.ShowDialog();
每当执行任务时,您需要保持对对话框的1个引用。如果您每次要在该表单上操作时都这样做:
BookList bookList = new BookList();
您实际上是在创建完全不同的表单副本。
答案 1 :(得分:1)
您正在创建一个新的BookList,然后在方法返回后立即丢失它。您是否尝试访问BookEntry表单中的BookList对象?它看起来应该更像:
private void btnEnter_Click(object sender, EventArgs e)
{
// bookListForm is the ID of the form in the designer
bookListForm.txtBookList.Text="aaa";
}
答案 2 :(得分:1)
你在BookList表单上的.Show()。确保您没有创建表单的2个单独实例,并将文本框设置为一个但显示另一个(这是我怀疑的)。