Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hii,everyone
How to solve this error(an unhandled exception of type 'System.FormatException'...)

in button search when put characters give me this error .


SQL
da.SelectCommand = new SqlCommand("select * from tblcontacts where id like " +Int32.Parse( textBox3.Text), cs);
            dt.Clear();
            da.Fill(dt);

            dataGridView1.DataSource = dt;
Posted

There is no need to convert to an integer just to convert it back to a string again. Just use:

C#
new SqlCommand("select * from tblcontacts where id like " + textBox3.Text, cs)


But you should learn about parameterized queries and SQL injection attacks. This opens you up to major hacking in your database.
 
Share this answer
 
Comments
mhassan083 15-Jan-14 11:33am    
when try it give me error ('System.Data.Sqlcient.SqlException'...invalid column name 'mh').
Christian Graus 16-Jan-14 17:13pm    
That means that your text was not just a number. There's no way adding a number to this SQL, would give that error.
Try this


as Ron said , be aware of SQL_injection[^]

SQL
string query = string.Format("select * from tblcontacts where id like '{0}'",textBox3.Text);
       da.SelectCommand = new SqlCommand(query, cs);
 
Share this answer
 
v2
Comments
mhassan083 15-Jan-14 11:28am    
there is three braces make error
Karthik_Mahalingam 15-Jan-14 11:43am    
if your issue is resolved, pls close this post..
mhassan083 15-Jan-14 12:00pm    
not resolved
your solution make error
Karthik_Mahalingam 15-Jan-14 12:03pm    
what error you are getting
mhassan083 16-Jan-14 1:29am    
error before running under brace " ' "),cs); have red line under it
If you're doing a like statement, that suggests to me that you are trying to pass multiple values across from your textbox through to your SQL. If you are trying to validate anything other than an integer with Int32.Parse, this will fail. A couple of things need to be considered:

  1. Rather than passing parameters like this, you should consider parameterised queries because you have left the code open to SQL Injection attacks[^] (you're lucky that the Int32.Parse is throwing an exception as that has, by accident, acted as protection for your database).
  2. Is a like statement really the best way to do this? Consider the execution query you will end up with. You might want to put a table based query[^] in there instead.
 
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