C#加载事件未触发

Reg*_*Reg 4 c# event-handling

我正在学习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; }
    }

}

}
Run Code Online (Sandbox Code Playgroud)

这是我的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());

    }

}
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*sch 6

你做得非常奇怪,但问题的答案是你在使用以表格作为参数的构造函数时没有设置事件.您可以通过几种方式解决此问题.您可以在无参数构造函数中复制代码,也可以执行以下操作.注意: this()after构造函数,这将在使用参数执行构造函数之前调用无参数构造函数.

还要注意,我取出了额外的InitializeComponent,因为它将在无参数构造函数中执行.

public selectdb() 
{ 
    InitializeComponent(); 
    this.Load += new System.EventHandler(selectdb_Load); 
} 

private Form1 mainForm = null; 

public selectdb(Form callingForm) : this()
{ 
    mainForm = callingForm as Form1; 
} 
Run Code Online (Sandbox Code Playgroud)