Click here to Skip to main content
15,891,777 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private void textBox1_KeyUp(object sender, KeyEventArgs e)
       {
           len = Convert.ToInt32(textBox1.Text.Length);
           string str = "select SUBSTRING(F_Name,1,len) from Opd_Detail where F_name like'" + textBox1.Text + "'";
           textBox2.Text = str;
           c.con_open();
           SqlDataAdapter sda = new SqlDataAdapter(str, Con_Class.con);
           DataTable dt = new DataTable();
           sda.Fill(dt);
           dataGridView1.DataSource = dt;
           c.con_close();
       }

(error is tail in len)
Posted

1 solution

Well, yes. It would be:
C#
len = Convert.ToInt32(textBox1.Text.Length);
 string str = "select SUBSTRING(F_Name,1,len) from Opd_Detail where F_name like'" + textBox1.Text + "'";

len in your SQL statement is part of a string, so the characters 'l', 'e', and 'n' are passed to SQL, not the value of the len variable in the line above.
There are two ways to fix it:
1) Add the value instead of the name:
C#
len = Convert.ToInt32(textBox1.Text.Length);
 string str = "select SUBSTRING(F_Name,1," + len + ") from Opd_Detail where F_name like'" + textBox1.Text + "'";
But that's a bad idea - it's inefficient, and very dangerous.
2) Add it as a parameter to your SQL query - and at the same time protect your database! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead:
C#
string str = "SELECT SUBSTRING(F_Name,1,@LEN) FROM Opd_Detail FROM F_name like '%' + @COMP + '%'";
System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(str, Con_Class.con);
sda.SelectCommand.Parameters.AddWithValue("@LEN", textBox1.Text.Length);
sda.SelectCommand.Parameters.AddWithValue("@COMP", textBox1.Text);
You do realize that LIKE is a wild card match that only does anything useful if you include wildcards? (Which for SQL is a percent character)

[edit]Typos.[/edit]
 
Share this answer
 
v3

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