I’ve been trying to get this to work for a while but can’t (I am fairly new to C# and OOP in general).
Basically, I have this piece of code on a second form:
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");
}
}
It all runs fine and does what it’s supposed to, which is insert some data into a SQL database (I took that code out to make it a little cleaner). So after all that happens, I try to execute mainForm.refreshCall(). This refreshCall method exists on my first form, or mainForm, and looks like this:
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);
}
}
However, this.listParts.DataSource and this.listParts.DisplayMember both tell me that they are not valid static properties Error, static method, or static field initialize. I am absolutely baffled by what that means. If someone would be so kind as to shed some light on this for me, I would greatly appreciate it!
Your
refreshCallis marked asstatic, but you are referencing instantiated variables, in this case, yourListBox, so that won’t work. You either have to pass in the ListBox as a parameter reference, or just remove thestaticattribute.Simplest way:
then the method call changes to: