I try to make an app which manages client’s contacts. The form is very very simple. There are: panel (inside this panel are labels with names, emails, etc.) and a listbox which shows all saved contacts in sdf file. I have one big problem. I want to refresh the listbox content via a method in another class. I set the listbox as public, debugger shows no errors during the project build. When the form loads, this message is prompted (via try-catch exception): “Object reference not set to an instance of an object.”. I tried to do this project differently – everything was written in one class. Here’s the code:
database.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace Contacts
{
class Database
{
public static void RefreshListBox()
{
SqlCeConnection connection = null;
try
{
var form1 = Form.ActiveForm as Form1;
connection = new SqlCeConnection("Datasource = C:\\Kontakty.sdf");
connection.Open();
SqlCeCommand command = new SqlCeCommand("SELECT * FROM Contacts", connection);
SqlCeDataReader reader = command.ExecuteReader();
while (reader.Read())
{
form1.listBox1.Items.Add(reader.GetString(0) + " " + reader.GetString(1));
}
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Contacts
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Database.RefreshListBox();
}
}
}
Does anyone here know what is wrong?
PS: kontakty = contacts (in Czech ;-))
This might help:
And then:
Other than that, you really shouldn’t be passing forms or listboxes into database classes. It should be the other way around– your form should just get the data from the class and populate the listbox there.