I am creating a form in c#.net . I want to populate the gridview only on button click with entries meeting search criteria.
I have tried but on searching ID it works but on searching FirstName it gives error plz check SQL also.
Code behind:
private void button1_Click(object sender, EventArgs e)
{
try
{
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=L:/New project/Project/Project/Data.accdb";
string sql = "SELECT * FROM AddressBook WHERE FirstName='" + textBox1.Text.ToString();
OleDbConnection connection = new OleDbConnection(strConn);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "AddressBook");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "AddressBook";
}
catch (System.Exception err)
{
this.label27.Visible = true;
this.label27.Text = err.Message.ToString();
}
}
you forgot databind();
but remember this sql query is vulnerable to SQL injections so make sure after all works to filter out bad characters
Your error was produced because you did not close your query
FirstName='" + textBox1.Text.ToString();should beFirstName='" + textBox1.Text.ToString() + "'";but like that you must type exactly the right namewith using “like” you can get more results
And
ToString()is not needed since the Text Property is already a string