Click here to Skip to main content
15,922,894 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have a Windows form with a textbox named "txtSearch". I want to retrieve data based on value inside this textbox. However I get error "Fatal error encountered while executing command". The search result is supposed to be on a DataGridViewer.

My code is as below (Connection string is removed) :

C#
try
{
dataGridView1.Visible = true;
BindingSource bs = new BindingSource();
DataTable newadm = new DataTable();
String term = txtSearch.Text;
string db = ----Connection String Goes Here----;

bs.DataSource = newadm;
this.dataGridView1.DataSource = bs;

MySqlConnection conn = new MySqlConnection(db);
conn.Open();

string s = "select * from newadm where firstname like @term OR lastname like @term";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@term", MySqlDbType.VarChar, 40).Value = "%" + txtSearch.Text + "%";

MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand(s, conn);

da.Fill(newadm);
da.Update(newadm);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}


If I remove the placeholders (@term), with an actual value, this works just fine. Any assitance will be greatly appreciated.

Thanks in advance.
Posted
Updated 5-Jul-12 6:34am
v2
Comments
Sandeep Mewara 5-Jul-12 11:03am    
Is this working fine when you run on your DB:
select * from newadm where firstname like '%sometext%' OR lastname like '%sometext%'

You need to put single quotes around @term in string s.

However, I hope this is not the real code because you are exposing the database to SQL injections.
 
Share this answer
 
Replace the code

C#
da.SelectCommand = cmd;
 
Share this answer
 
Hi Sandeep,

The SQL commands are working perfectly on the DB directly.
If I remove the placeholders and give an actual value, the program works properly.
Only with placeholders, the command execution fails.

Hi ryanb31,

I have already tried it, but it does not work. It returns empty dataset.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900