-2

Getting this error, already did some research but i cant fix it, if someone can help me:

The error:

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication2.exe

Additional information: Object reference was not defined as instance of a object.

It Happens on con.Open();

My Code:

    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;

namespace WindowsFormsApplication2
    {
            public partial class Form1 : Form
            {
                SqlConnection con;
                SqlDataAdapter adap;
                DataSet ds;

    public Form1()
    {
        InitializeComponent();
    }

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

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

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con;
            SqlDataAdapter adap;
            DataSet ds;
            con = new SqlConnection();
            con.ConnectionString = (@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Duarte\Documents\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\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 button4_Click(object sender, EventArgs e)
    {
            AdicionarPagamento add2 = new AdicionarPagamento();
            add2.ShowDialog();
    }

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

    private void button5_Click(object sender, EventArgs e)
{
        foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
         {
             dataGridView1.Rows.RemoveAt(item.Index);
         }
}

    private void search()
    {

    con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from Pagamentos where name like ('" + textBox1.Text + "%')";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        dataGridView1.DataSource = dt;

        con.Close();
    }
    private void textBox1_TextChanged (object sender, EventArgs e)
    {
        search();


    }

    private void button2_Click(object sender, EventArgs e)
    {

    }
    }
    }

I want to make a search in real time as soon as i write a letter the program shows the the data beginning with that letter.

Community
  • 1
  • 1
  • possible duplicate of [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) – Otiel Apr 28 '15 at 20:02
  • Null reference are always the same thing. Read that link thoroughly. You have an object whose value is null, but you are trying to reference a method (in this case `Open`) on that null value. – crthompson Apr 28 '15 at 20:03
  • Scope is also something to learn about in this case. Just because you new up an object in one method, does not mean that it can be seen in another method, quite the contrary. – crthompson Apr 28 '15 at 20:06
  • Can you share the full `ToString()` output of the exception, including the complete traceback? I see multiple calls to `con.Open()` – dbc Apr 28 '15 at 20:06

1 Answers1

0

you are creating a new reference for the connection object in the Form1_Load. try this in the Form_Load method:

    try
    {

        SqlDataAdapter adap;
        DataSet ds;
        this.con = new SqlConnection();
        this.con.ConnectionString = (@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Duarte\Documents\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\PAPPloran.mdf;Integrated Security=True;Connect Timeout=30");
        this.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);

    }

or create a new instance in the search method.

assaf
  • 210
  • 2
  • 9
  • [`SqlConnection`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection%28v=vs.110%29.aspx) is disposable so better to use and dispose a local variable and eliminate the class variable entirely. – dbc Apr 28 '15 at 20:08