Searching using like - c#

When I'm searching my datagrid, it should be always the first word to type. If i type the next word or consecutive letter it contains, it doesn't show.
Example:
I'm going to search Welcome Back. If i type "Elcome" or "back", it doesn't show.
Here is my code...
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From books where Author like ('" + textBox1.Text + "%')";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;

It is because you are telling the database to select rows that starts with textBox1.Text followed by anything else (%) you should change it to
"Select * From books where Author like ('%" + textBox1.Text + "%')";
this will find all books that their authors have textBox1.Text somewhere in their value.
In like command % can be replaced by zero or more character.
Also try using parameterized queries, your code is vulnerable to SQL injection.

Related

Sql to select the prerequisite of a certain course

I have a table that has courses details as follows:
And, in the Windows, form I placed a textBox and a button, when a student writes the name of the course to see the prerequisite requirement of that course as follows:
So I tried using the following code:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select Name from Courses where (Name = '" + textBox2.Text + "') and Preq = Code";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView3.DataSource = dt;
conn.Close();
textBox2.Text = "";
However, the code gives me the name column without any data as follows:
Also, is there a way to show a message when the course does not have any requirement such as " this course has no prerequisite requirement " something like that?
your query is wrong , the below query returns the list of courses that are requirement for the given course name :
select Name from Courses
where code IN ( select PREQ from Courses where
Name = '" + textBox2.Text + "')
also It would be easier to handle showing a message in your c# code to show if there is no preq.you can checking if dt is null or not .

C# Filter search Datatable with multiple rows using one textbox

I have created a filter search for my attendance monitoring system , it searches by the employee name but not with other fields, I think I'm gonna use the LIKE keyword but I don't know how to do it. Here's my code
private void textBox1_TextChanged(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "SELECT * FROM tblEmployee WHERE [Firstname] like #1";
command.parameters.AddWithValue("#1",textBox1.Text);
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Update();
dataGridView1.Refresh();
connection.Close();
}
The behaviour matches exactly with the query you wrote, you should rewrite the query to match your requirements:
string query = "SELECT * FROM tblEmployee WHERE [Firstname] like '%' + #1 + '%' OR [OtherColumn] LIKE '%' + #1 + '%'";
BTW, I have changed slightly your LIKE to make it behave like a 'it does contain XXX'.

How can i get the value of column field base on another column field

Im using Visual Studio C# and using Access as my database. I have two columns, ItemCode and ProductName. I want to auto input of the productname on its textbox whenever its itemcode was selected. how can I do this?
some codes:
try
{
con.Open();
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode='" + txtItem.Text + "'");
command.Connection = con;
command.Parameters.AddWithValue("itemcode", txtItem.Text);
OleDbDataReader reader = command.ExecuteReader();
if (reader.Read())//Update Item Code is already exist
{
.........
Feel free to edit my question and please be kind. thank you guys
Try this .
text_box.Text=reader["ProductName"].ToString();
You are filtering the rows by specifying the ItemCode in the Where clause, So The reader will contains the corresponding row/s that matches the specified code. What you need to do is Access the required column value by specifying the name as like the above snippet.
For extracting data from database, I prefer that use OleDbDataAdapter.
You can simply use:
string command = #"Select * from TblInventory where ItemCode='" + txtItem.Text + "'";
OleDbDataAdapter da = new OleDbDataAdapter(command, con);
DataTable dt = new DataTable();
da.Fill(dt);
Now, use dt :
if (dt.Rows.Count == 0)
//Error Message
else
cmbTreatyTitle.Text = dt.Rows[0]["ProductName"].ToString();
I hope this is helpful.

"An expression of non-boolean type specified" error executing SQL from .Net

I am getting this error:
An expression of non-boolean type specified in a context where a
condition is expected, near 'likeram'.
I entered "ram" in txt_name:
SqlConnection con = new SqlConnection(
#"Data Source=DELL_LAPTOP\sqlexpress;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name like" + txt_name.Text, con);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
You're missing a space between the like and the string concatentation and the quotation mark around the parameter:
SqlDataAdapter SDA = new SqlDataAdapter(
string.Format("SELECT *
FROM newproj
WHERE name like '{0}'" txt_name.Text), con);
Though I'd advise you not to use that method as it is prone to SQL injections. Use SQL Parameters instead:
SqlCommand command = new SqlCommand("SELECT * FROM newproj where name like #text");
command.Parameters.AddWithValue("text", txtName.Text);
var sqlAdapter = new SqlDataAdapter(command);
You're missing ' quotes inside the string, but you shouldn't be inserting text into your SQL queries like this anyway, as they're a major SQL-injection risk:
You also need to make sure that % characters are included with the like as otherwise it will only find exact matches:
var dt = new DataTable();
using(var con = new SqlConnection(#"...")
using(var cmd = new SqlCommand(#"
select *
from newproj
where name like '%' + #text + '%'") // Add % wildcards
{
cmd.Parameters.AddWithValue("text", txtName.Text); // Safe from SQL injection
var sda = new SqlDataAdapter(command);
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
Also note that you should always dispose of your SQL command and connection objects, and that using is the best way to do this.
You missed space and single qoute in query
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name like '" + txt_name.Text+"'", con);
you are using 'like' in where condition but you didn't added wild chars, if you want exact match records, no need of 'like' use 'name= '
like below
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name = '" + txt_name.Text+"'", con);
if you want to search with name like use below
SqlDataAdapter SDA = new SqlDataAdapter(
"SELECT * FROM newproj where name like '%" + txt_name.Text+"%'", con);

asp.net - searching for a data containing an apostrophe in the database

Good day! I am having a hard time fixing this problem. I've been searching the answer for this but seemed to be very very hard to look for the most fitting answer.
i use this query to search for a tenant's name based on what the user inputs in the txtSearchRP textbox, it works very well to data with no apostrophe in it, however when the user searches for a name containing ' , it does not function well.
example: user inputs MAX'S to search MAX'S RESTAURANT
SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Thanks for your help in advance!
edit for more information:
I am actually passing the query to sqlDataSource to bind the gridview automatically after the user click THE BUTTON.
SqlDataSource3.SelectCommand = SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Try this
conn = new
SqlConnection("ConnectionString");
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT * from tenant WHERE (name LIKE #tenant)", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "#tenant";
param.Value = "%" + txtSearchRP.Text + "%"; // you can use any wildcard operator
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
In addition to the answers already given, in some applications, you might need to consider escaping wildcards such as % in the input string provided by the user.
For example, if the user enters "25%", then matching on "%25%%" will return values that contain "25", rather than restricting to values that contain "25%".
You can escape wildcards as follows (for SQL Server):
string value = ... value entered by user;
value = value.Replace("[", "[[]");
value = value.Replace("_", "[_]");
value = value.Replace("%", "[%]");
Better way create storedprocedure
SP :
Create proc sp_Search( #txtSearch nvarchar(150))
as begin
SELECT * from tenant WHERE name like #txtSearch+'%'
end
Code behind :
string txtSearch = txtSearchRP.Text;
SqlDataReader dr;
using (SqlConnection conn = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmdd = new SqlCommand())
{
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = conn;
conn.Open();
dr = cmdd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
var name = dr["name"].ToString();
var location = dr["location"].ToString();
}
} dr.Close();
conn.Close();
}
}
Updated:
Write a function which returns datatable so that we can bind it to our gridview control as i did in code below
public DataTable bindGridView()
{
string txtSearch = txtSearchRP.Text;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
SqlCommand cmdd = new SqlCommand();
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = con;
con.Open();
SqlDataAdapter dap = new SqlDataAdapter(cmdd);
DataSet ds = new DataSet();
dap.Fill(ds);
dt = ds.Tables[0];
con.Close();
}
return dt;
}
On Button click : Call bindGridView() function for binding Gridview control
GridView1.DataSource = bindGridView();
GridView1.DataBind();
thanks to all who shared their knowledge and effort, finally got the answer through the String replace method
HERE'S THE 3-LINED CODE
string value = txtSearchRP.Text;
value = value.Replace("'", "['']");
sqlDataSource3.SelectCommand = "SELECT * from tenant WHERE (name LIKE '%" + value.ToString() +"%')";
through the joined effort, answers you posted here, we solve the problem in the simplest form :)

Categories

Resources