Reputation: 181
I am developing an application in C# VS 2010.
I am using CE database to this. My code to search a string from database is
string con = @"Data Source=|DataDirectory|\Database\Acadamy.sdf;Persist Security Info=False";
string cmd = "SELECT sid AS [Student ID], sname AS [Student Name], contact AS [Contact No] FROM Student WHERE sname LIKE '%'+ @name +'%'";
var dt = new DataTable();
using (var a = new SqlCeDataAdapter())
{
try
{
a.SelectCommand = new SqlCeCommand();
a.SelectCommand.Connection = new SqlCeConnection(con);
a.SelectCommand.CommandType = CommandType.Text;
a.SelectCommand.CommandText = cmd;
a.SelectCommand.Parameters.AddWithValue("@name", textBox1.Text);
a.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I input any string like as
I am getting error System.FormatException: @name : as - Input string was not in a correct format.
What will be the error unable to fix.
Upvotes: 3
Views: 602
Reputation: 216343
Remove the quoting from the sql command text.
Parameters are invaluable also for helping to avoid that confusion.
Add the wildcard chars to the parameter value....
string cmd = "SELECT sid AS [Student ID], sname AS [Student Name], " +
"contact AS [Contact No] FROM Student WHERE sname LIKE @name";
....
a.SelectCommand.Parameters.AddWithValue("@name", "%" + textBox1.Text + "%") ;
Upvotes: 5