从子窗体调用父窗体上的方法
本文关键字:窗体 方法 调用 | 更新日期: 2023-09-27 18:24:00
我已经试着让它工作了一段时间,但做不到(我对C#和OOP还很陌生)。
基本上,我在第二个表单上有这段代码:
private void button1_Click(object sender, EventArgs e)
{
if (charCount > 2 && charCount < 30)
{
try
{
conn.Open();
}
catch (Exception ex)
{
//Error handling code here
}
finally
{
conn.Close();
}
//Run the SQL statements
try
{
//SQL insert data is here
}
catch (Exception ie)
{
MessageBox.Show(ie.Message);
}
finally
{
//Close the connection
if (conn.State != ConnectionState.Closed)
{
conn.Close();
}
mainForm.refreshCall();
this.Close();
}
}
else
{
MessageBox.Show("Part numbers can be between 2 and 30 characters.'n Yours was " + charCount + " characters long.", "Error");
}
}
它运行良好,并完成了它应该做的事情,即将一些数据插入到SQL数据库中(我把代码去掉是为了让它更干净一点)。因此,在所有这些发生之后,我尝试执行mainForm.refreshCall()
。这个refreshCall方法存在于我的第一个表单,即mainForm
上,看起来像这样:
public static void refreshCall()
{
SqlConnection conn = new SqlConnection("Data Source=DSERVER''NEW_SQL;Initial Catalog=AWSoftware;Integrated Security=True");
try
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT part_num from dbo.CustomParts", conn);
adapter.Fill(ds);
this.listParts.DataSource = ds.Tables[0];
this.listParts.DisplayMember = "part_num";
conn.Close();
}
catch (SqlException odbcEx)
{
MessageBox.Show("There was an error connecting to the data source'nError Code: 1001", "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
但是,this.listParts.DataSource
和this.listParts.DisplayMember
都告诉我,它们不是有效的静态属性Error、静态方法或静态字段initialize。我完全不明白这意味着什么。如果有人能为我阐明这一点,我将不胜感激!
您的refreshCall
被标记为static
,但您引用的是实例化的变量,在本例中是ListBox
,因此这将不起作用。您必须将ListBox作为参数引用传入,或者只移除static
属性。
最简单的方法:
public void refreshCall() {
// blah-blah
}
则方法调用更改为:
this.refreshCall();