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.