search with multi textbox windows form c# - 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";
}
}

Related

How do i show record not found message when serach result not found in c# windowsforms

try
{
SqlConnection con = new SqlConnection("data source=DESKTOP-28VA3GI;database=EMPLOYEES;integrated security=true");
SqlCommand cmd = new SqlCommand("select * from emp where ename like '" + textBox1.Text + "%' or eno like '" + textBox1.Text + "%' or phone like '" + textBox1.Text + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "e");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "e";
}
catch ( )
{
}
Are you trying to get multiple table at once? If yes then you can use dataset else you can use datatable.
In case you opt for dataset you can find the number of rows in tables you are getting by using ds.Tables(i).Rows.Count. (i --> index of the table which you want to check).
In case you opt for datatable (dt) you can find number of rows by dt.Rows.Count.
Based on the result you can show your message.

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;
}

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?

invalid column name search error

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());
}
}

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