Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException was unhandled - what is null?

Tags:

c#

winforms

I'm trying to access an event in my main form by clicking a button (btnsearch_Click) and everytime I clicked it, it says 'object reference not set to an instance of an object'.

Here is my code:

USER CONTROL

namespace Purchase_Order
{
    public partial class Search : UserControl
    {
        public event EventHandler btnSearchClicked;

        public Search()
        {
            InitializeComponent();
        }
        private void btnsearch_Click(object sender, EventArgs e)
        {

           btnSearchClicked(sender, e);
        }
   }
}

MAIN FORM

namespace Purchase_Order
{
    public partial class formMain : Form
    {

        public formMain()
        {
            InitializeComponent();            
        }




 private void formMain_Load(object sender, EventArgs e)
        {

Search searchbox = new Search();
searchbox.btnSearchClicked += new EventHandler(SearchClicked);
}


 void SearchClicked(object sender, EventArgs e)
        {
            MySqlConnection con = new MySqlConnection(serverstring);

            try
            {

                string query = "SELECT * FROM tblclassification WHERE INSTR(class_name, @search)";

                MySqlCommand cmd = new MySqlCommand(query, con);
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);

                Search content = new Search();
                cmd.Parameters.AddWithValue("@search", content.btnsearch.Text);

                DataTable dt = new DataTable();
                da.Fill(dt);


                classification control = new classification();
                control.dataGridView1.DataSource = dt;
                control.dataGridView1.DataMember = dt.TableName;

                panelMain.Controls.Clear();
                panelMain.Controls.Add(control);
                MessageBox.Show("OK");

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }    
        }
like image 757
Harvey Avatar asked Jul 18 '26 16:07

Harvey


1 Answers

You are creating a new instance of your user control in SearchClicked method and you are not registering the event against it.

Search content = new Search();

Also its better if you check whether any control has register your event before raising it like:

private void btnsearch_Click(object sender, EventArgs e)
{
 if(btnSearchClicked != null)
       btnSearchClicked(sender, e);
}
like image 172
Habib Avatar answered Jul 20 '26 04:07

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!