0

i am trying to edit data from a database directly on datagridview, but for some reason im having a error.

Object reference not set to an instance of an object

I tried some differents approach but didn't worked, had the same error.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Threading;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication2
{
    public partial class Principal : Form
    {
        SqlConnection con;
        SqlDataAdapter adap;
        SqlCommandBuilder scb;
        DataSet ds;
        SqlCommandBuilder cmdb1;

        public Principal()
        {
            InitializeComponent();
            Load += new EventHandler(Principal_Load);
        }


        private void fusionButton1_Click(object sender, EventArgs e)
        {
            AdicionarFornecedor add = new AdicionarFornecedor();
            add.ShowDialog();
        }

        private void fusionButton2_Click(object sender, EventArgs e)
        {
            VerFornecedores add = new VerFornecedores();
            add.ShowDialog();
        }

        private void Principal_Load(object sender, EventArgs e)
        {
            try
            {
                SqlConnection con;
                SqlDataAdapter adap;
                DataSet ds;
                con = new SqlConnection();
                con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
                con.Open();
                adap = new SqlDataAdapter("select * from Pagamentos", con);
                ds = new System.Data.DataSet();
                adap.Fill(ds, "P");
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }


        }

        private void fusionTheme1_Click(object sender, EventArgs e)
        {

        }

        private void fusionButton3_Click(object sender, EventArgs e)
        {
            AdicionarPagamento add2 = new AdicionarPagamento();
            add2.ShowDialog();
        }

        private void fusionButton4_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
            con.Open();
            SqlCommand cmd = new SqlCommand(@"delete from Pagamentos WHERE (IdFornecedor = '" + textBox3.Text + "')", con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Dados Eliminados com Sucesso ! ");
            textBox3.Text = "";
            con.Close();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            con = new SqlConnection();
            con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from Pagamentos where NomeFornecedor like ('" + textBox1.Text + "%')";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;

            con.Close();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void fusionButton5_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
                if (row.Cells[7].Value != null && row.Cells[7].Value.ToString() == "1- Pago")
                {
                    row.DefaultCellStyle.BackColor = Color.GreenYellow;

                }
                else 
                {
                    row.DefaultCellStyle.BackColor = Color.Tomato;
                }
        }

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;
        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        private void fusionTheme1_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
        }

        private void fusionButton6_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, DataGridViewCellFormattingEventArgs e)
        {
        }

        private void fusionButton7_Click(object sender, EventArgs e)
        {
            SqlConnection con;
            SqlDataAdapter adap;
            DataSet ds;
            con = new SqlConnection();
            con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
            con.Open();
            adap = new SqlDataAdapter("select * from Pagamentos", con);
            ds = new System.Data.DataSet();
            adap.Fill(ds, "P");
            dataGridView1.DataSource = ds.Tables[0];
        }

        private void fusionButton8_Click(object sender, EventArgs e)
        {
            con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
            con.Open();
            SqlCommand cmd = new SqlCommand(@"delete from Pagamentos WHERE (NomeFornecedor = '" + textBox3.Text + "')", con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Dados Eliminados com Sucesso ! ");
            textBox3.Text = "";
            con.Close();
        }

        private void Principal_Load_1(object sender, EventArgs e)
        {
        }

        private void fusionButton9_Click(object sender, EventArgs e)
        {
            try
            {
                cmdb1 = new SqlCommandBuilder(adap);
                adap.Update(ds);
                MessageBox.Show("Data updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
    }

https://i.stack.imgur.com/1lSIl.png

  • On which line exactly? BTW, [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Jul 01 '15 at 14:22
  • I added a link to the error image. – Duarte Andrade Jul 01 '15 at 14:25
  • No, debug your code and see which line throws this exception. – Soner Gönül Jul 01 '15 at 14:30
  • I run in debug mode (F5) but here is no error or warning that i can see.. – Duarte Andrade Jul 01 '15 at 14:36
  • Does the exception appears just after load or following some user action(s) ? May you explain the sequence of user actions ? Did you defined other events related to DataGridView ? – Graffito Jul 01 '15 at 20:05
  • Hello, it happens when the user press the "save" button, pretty sure its fusionButton9_Click causingerror, check that pls, i edited the code, the previous wasnt from the same project, sorry. – Duarte Andrade Jul 02 '15 at 14:47
  • silly question.... can you check if `Principal_Load` is being executed at all? And also can you debug and check which line is causing the exception before it goes to catch block? – Chetan Feb 26 '17 at 04:38

0 Answers0