invalid column name search error - c#

I am trying to get search query
Its in asp.net c# please help me for search query.
protected void btnreg_Click(object sender, EventArgs e)
{
string search = query.Text;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE search LIKE '%' + nor + '%' OR recipe LIKE '%' + search + '%' OR ingredients LIKE '%' + search + '%' OR type_of_food LIKE '%' + search + '%' OR type_of_meal LIKE '%' + search + '%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}}

I suppose 'nor' is a column name in your table .. try the following :-
protected void btnreg_Click(object sender, EventArgs e)
{
string search = query.Text;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '%'" + search + "'%' OR recipe LIKE '%' "+ search + "'%' OR ingredients LIKE '%' "+ search + "'%' OR type_of_food LIKE '%' "+ search + "'%' OR type_of_meal LIKE '%' "+ search +" '%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}
}
Actually you cannot enclose the varibale search inside the "double quotes" tag .
Hope this helps you .
Cheers !

Why not use Parameterized Queries !
E.g
var command = "SELECT * FROM recipe WHERE recipe LIKE '% #Receipe %'";
var cmd= new SqlCommand(command , yourconnetion);
cmd.Parameters["#Receipe "].Value =query.Text;
OR
cmd.Parameters.AddWithValue("#Receipe ",query.Text);
Read more about How and Why to Use Parameterized Queries

Finally I got the right one, it goes like this.
Although thanks for help guys.
protected void btnreg_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '%" + query.Text + "%' OR recipe LIKE '%" + query.Text + "%' OR ingredients LIKE '%" + query.Text + "%' OR type_of_food LIKE '%" + query.Text + "%' OR type_of_meal LIKE '%" + query.Text + "%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}

Use `Parametarized` and `Using{}` statement to auto dispose and close connection
using( SqlConnection objConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"))
{
objConnection.Open();
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '% #query %'" , con))
DataTable dt= new DataTable();
da.SelectCommand.Parameters.AddWithValue("#query",query.Text);
da.Fill(dt);
}
catch(System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}

Related

Query database by textbox

I need to query my database for found person by keyin name " space " surname, name and surname are both in different column in the same table.
When user key in in textbox, query must be some thing like:
string valueToSearch = MyTextBox.Text.ToString();
searchUserData(valueToSearch);
public void searchUserData(string valueToSearch)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = MyConstring;
string searchQuery = "SELECT [NDM],[Prenom],[Nom],[Sex],[DateNaiss],[Adresse],[Tel] FROM [Lab062016].[dbo].[LabPatients] WHERE Nom LIKE '%" + valueToSearch + "%' OR Prenom LIKE '%" + valueToSearch + "%' ";
SqlCommand cmande = new SqlCommand(searchQuery.ToString(), conn);
SqlDataAdapter adapter;
DataTable table;
adapter = new SqlDataAdapter(cmande);
table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}

search with multi textbox windows form c#

public void filter()
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
SqlDataAdapter sqlad = new SqlDataAdapter("select * From Customer", sqlconn);
DataTable dtbl = new DataTable();
sqlad.Fill(dtbl);
DataView dv = dtbl.DefaultView;
dv.RowFilter = string.Format("Name like '%{0}%' and Address like '%{0}% and office_number like '" + searchoffice.Text + "%'and phone_number like '" + searchphone.Text + "%' and acount_name like '%{0}%'", searchname.Text,searchaddress.Text,searchoffice.Text,searchphone.Text,searchaccountname.Text);
customergrid.DataSource = dv.ToTable();
dtbl.DefaultView.Sort = "[Name] DESC";
}
}
When I run this method in the textbox.textchange()-EventHandler, I get following Exception:
The expression contains an invalid string constant: '
Please help me fix the exception.
It seems that your query string was missing one space near office_number like '" + searchoffice.Text + "%' and phone_number, also there was one '-character missing and String.Format- parameter count mismatch.
So try following:
public void filter()
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
SqlDataAdapter sqlad = new SqlDataAdapter("select * From Customer", sqlconn);
DataTable dtbl = new DataTable();
sqlad.Fill(dtbl);
DataView dv = dtbl.DefaultView;
dv.RowFilter = string.Format("Name like '%{0}%' and Address like ‘%{1}%’ and office_number like '" + searchoffice.Text + "%' and phone_number like '" + searchphone.Text + "%' and acount_name like '%{0}%'", searchname.Text,searchaddress.Text);
customergrid.DataSource = dv.ToTable();
dtbl.DefaultView.Sort = "[Name] DESC";
}
}

Repeater Search Query String

How can I make my select line in C# check if news_title is like my query string named Search?
This is what I have tried without success. It's supposed to then fill a Repeater with results that are like the query string.
// Get data from database/repository
static DataTable GetDataFromDb()
{
string searchquery = HttpContext.Current.Request.QueryString["Search"].ToString();
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
con.Open();
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE ([news_title] " +
"LIKE '%' + " + searchquery + " + '%') Order By news_postdate", con);
var dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
It should be '%" + searchquery + "%'. However this kind of string concatenation is open for SQL injection. Try parameterized queries instead, something like this :
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title] " +
"LIKE #Search Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search","%" + searchquery + "%");
Or:
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title]" +
" like '%' + #Search+ '%' Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search",searchquery);
Although specify the type directly and use the Value property is more better than AddWithValue. Have a look at this Can we stop using AddWithValue() already?

Searching a character in sql table and displaying all records in gridview that start with that character ASP.NET c#

Good day I am working on an ASP.NET C# application that searches a sql table and brings back the results in a gridview. I got it to work using the like operator but I realise that if I search a character it brings back any record with that character in it, what I want is if I search with a character I want all records starting with that character. It should also allow me to search normally, Here is what I did previously
//I have a connection manager class in my app code folder
SqlConnection connection = connectionManager.GetConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = connection;
String str = "select PR_NAME_GN, PR_NAME_SURN, EVENT_PARISH, EVENT_YEAR, EVENT_TYPE, FS_IMAGE_ID from Jam01 where (PR_NAME_GN like '%' + #deceasedFirstName + '%' AND PR_NAME_SURN like '%' + #deceasedLastName + '%' AND EVENT_PARISH like '%' + #ParishOfDeath+ '%' AND EVENT_YEAR like '%' + #YearOfDeath+ '%' AND EVENT_TYPE like '%' + #TypeDeath+ '%' AND FS_IMAGE_ID like '%' + #ImgLocation+ '%')";
SqlCommand command = new SqlCommand(str, connection);
command.Parameters.Add("#deceasedFirstName", SqlDbType.NVarChar).Value = DeathFirstNametbox.Text;
command.Parameters.Add("#deceasedLastName", SqlDbType.NVarChar).Value = DeathLastNametbox.Text;
command.Parameters.Add("#ParishOfDeath", SqlDbType.NVarChar).Value = ParishoDeathtbox.Text;
command.Parameters.Add("#YearOfDeath", SqlDbType.NVarChar).Value = YearofDeathtbox.Text;
command.Parameters.Add("#TypeDeath", SqlDbType.NVarChar).Value = type_Death.Text;
command.Parameters.Add("#ImgLocation", SqlDbType.NVarChar).Value = "";
command.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataSet ds = new DataSet();
sda.Fill(ds, "PR_NAME_GN");
sda.Fill(ds, "PR_NAME_SURN");
sda.Fill(ds, "EVENT_PARISH");
sda.Fill(ds, "EVENT_YEAR");
sda.Fill(ds, "EVENT_TYPE");
sda.Fill(ds, "FS_IMAGE_ID");
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
I need recommendation on how to rework the sql statement. I am kinda new to this so please bear with me.
Remove the leading % wildcard after the LIKE keyword so that only values starting with the specified value will be returned:
String str = "SELECT PR_NAME_GN, PR_NAME_SURN, EVENT_PARISH, EVENT_YEAR, EVENT_TYPE, FS_IMAGE_ID FROM Jam01 WHERE (PR_NAME_GN LIKE #deceasedFirstName + '%' AND PR_NAME_SURN LIKE #deceasedLastName + '%' AND EVENT_PARISH like #ParishOfDeath + '%' AND EVENT_YEAR LIKE #YearOfDeath+ '%' AND EVENT_TYPE LIKE #TypeDeath+ '%' AND FS_IMAGE_ID LIKE #ImgLocation + '%');";

datalist contol doesn't bind

I have to bind the datalist control as per the values inserted in the form of find frined.
here is my code:
protected void search_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mahi\Documents\Visual Studio 2010\Projects\fc 6-4\fc\App_Data\fc.mdf;Integrated Security=True;User Instance=True");
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlCommand cmd = new SqlCommand(str, cn);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
}
There are few things I have noticed:
-First of all, you are highly vulnerable to sql-injection attacks as you are passing user entered values directly into the database. You can avoid this by using a parameterised query.
-Secondly, you need to filter the records in a WHERE clause. At the moment you are assigning user typed/selected values into a select query.
-And you need to use SelectedValue of dropdown list not SelectedItem
-Also you can use using() blocks to get SqlConnection and DataAdapter Disposed at the end.
Try this (Please replace col1, col2 as required and complete the query assigning all parameters):
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection("your_conn_string"))
{
string str = "Select Col1, Col2,... From profile " +
"Where unm = #unm and university= #uni and " +
"..." +
"ybatch = #ybatch";
SqlCommand cmd = new SqlCommand(str, cnn);
cmd.Parameters.AddWithValue("#unm",funm_txt.Text);
cmd.Parameters.AddWithValue("#uni",DDLuni.SelectedValue);
...
cmd.Parameters.AddWithValue("#ybatch",DDLbtch.SelectedValue);
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = cmd;
cnn.Open();
adapter.Fill(dt);
}
}
DataList1.DataSource =dt;
DataList1.DataBind();
try this,
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
da.fill(dt);
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
Add following code:
Your SqlDataAdapter and SqlCommand is not communicating.
and you haven't filled Datatable with the result.
da.SelectCommand = cmd;
da.fill(dt);

Categories

Resources