0

Good day everyone,

I am trying to build a c# GUI that will interact with a MySQL database. I would like to be able to insert, update and remove records via the Data Grid View component. Similarly, how you would double click to enter values in a new row in MySQL Workbench grid and then click the Apply button to execute the SQL statement.

Now I have written some code that pulls up the data grid view when the GUI is executed, however the code that I wrote to update and delete records does not work, specifically the below line. The delete method does it job with deleting the highlighted row, but as the below line is reached an object ref error occurs. I think I have referenced everything correctly but it seems not. Any suggestions will be much appreciated! Thank you for your time:

sqlData.Update(dataTable);

The error I get is: Object reference not set to an instance of an object

The methods which are in question below:

private void bttnSave_Click(object sender, EventArgs e)
    {
        try
        {
            sqlData.Update(dataTable);
        }
        catch (Exception eobj)
        {
            MessageBox.Show(eobj.Message.ToString());
        }
    }

    private void bttnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index); // remove highlighted row on data grid view
            sqlData.Update(dataTable);
        }
        catch (Exception eobj)
        {
            MessageBox.Show(eobj.Message.ToString());
        }
    }

The GUI Load method:

private void MySQLGUI_Load(object sender, EventArgs e)
    {
        using (MySqlConnection mysqlConn = new MySqlConnection(connection))
        {
            mysqlConn.Open();
            MySqlDataAdapter sqlData = new MySqlDataAdapter("View_Users", mysqlConn); // execute store procedure
            sqlData.SelectCommand.CommandType = CommandType.StoredProcedure;

            dataTable = new DataTable();
            sqlData.Fill(dataTable);
            bindingSource = new BindingSource();
            bindingSource.DataSource = dataTable;

            dataGridView1.DataSource = bindingSource;
        }
    }
asleniovas
  • 193
  • 3
  • 21

0 Answers0