我正在學習C#並且在加載系統事件觸發時遇到問題。直到我將form1和form2連接在一起以在它們之間傳遞變量之前它工作正常。 IE從Form2上的選定項目在Form 1上設置標籤。謝謝你的幫助!C#加載事件不會觸發
這是我爲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());
}
}
}
看起來很清楚 - 你沒有在新的構造函數中掛接事件處理函數。 – Hogan