我正在学习C#并且遇到加载系统事件的触发问题。它工作正常,直到我将form1和form2链接在一起以在它们之间传递变量。 IE在form2上的选定项目上设置Form 1上的标签。谢谢你的帮助!
这是我的Form1代码:
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
selectdb selectdb = new selectdb(this); // this is the button that shows the form in question. It worked fine until I added the (this).
selectdb.Show();
}
public string LabelText
{
get { return label1.Text; }
set { label1.Text = value; }
}
}
}
这是我的Form2代码:
namespace WindowsFormsApplication5
{
public partial class selectdb : Form
{
public selectdb()
{
InitializeComponent();
//this.Name = "selectdb";
//this.Text = "selectdb";
this.Load += new System.EventHandler(selectdb_Load);
}
private Form1 mainForm = null;
public selectdb(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.mainForm.LabelText = listBox1.SelectedItem.ToString();
}
private void selectdb_Load(Object sender, EventArgs e)
{
// Microsoft Access provider factory
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DataTable userTables = null;
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"C:\\Database.accdb\";Persist Security Info=False;";
// We only want user tables, not system tables
string[] restrictions = new string[4];
restrictions[3] = "Table";
connection.Open();
// Get list of user tables
userTables = connection.GetSchema("Tables", restrictions);
}
List<string> tableNames = new List<string>();
for (int i = 0; i < userTables.Rows.Count; i++)
listBox1.Items.Add(userTables.Rows[i][2].ToString());
}
}
}
答案 0 :(得分:6)
你做得非常奇怪,但问题的答案是你在使用以表格作为参数的构造函数时没有设置事件。您可以通过几种方式解决此问题。您可以在无参数构造函数中复制代码,也可以执行以下操作。注意构造函数之后的: this()
,这将在使用参数执行构造函数之前调用无参数构造函数。
另请注意,我取出了额外的InitializeComponent,因为它将在无参数构造函数中执行。
public selectdb()
{
InitializeComponent();
this.Load += new System.EventHandler(selectdb_Load);
}
private Form1 mainForm = null;
public selectdb(Form callingForm) : this()
{
mainForm = callingForm as Form1;
}
答案 1 :(得分:1)
我认为您需要更改新的构造函数以调用默认构造函数,以便无论您如何到达那里,所有内容都已正确连接:
public selectdb(Form callingForm) : this()
{
mainForm = callingForm as Form1;
}
答案 2 :(得分:0)
可能的原因:form_load事件没有触发