How to Implement Multiple search in Asp.Net - asp.net

I want to Implement multiple search query system in Asp.Net where search input are in form of TEXTBOX and DROPDOWN LIST. Query should work in combination or indivisually to filter the data from SQL Server
and show in Gridview.
This Code Snippet is for filtering two Dropdown values:
if (Agree_type_srch.SelectedValue != null || Status_srch.SelectedValue != null)
{
if (Agree_type_srch.SelectedValue != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select *from EntryDatabase where Agree_type ='" + Agree_type_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else if (Status_srch.SelectedValue != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select *from EntryDatabase where Curnt_St ='" + Status_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
if (Agree_type_srch.SelectedItem.Text != null && Status_srch.SelectedItem.Text != null)
{
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand com = new SqlCommand("Select * from EntryDatabase where Agree_type ='" + Agree_type_srch.SelectedItem.Text + "'and Curnt_St ='" + Status_srch.SelectedItem.Text + "'", conn);
SqlDataAdapter sqldatad = new SqlDataAdapter();
DataSet ds = new DataSet();
com.Connection = conn;
sqldatad.SelectCommand = com;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
...

First, using string concatenation to provide parameters can result in SQL injection, use SqlParameter to pass parameters would be better.
Second, consider to warp all SqlClient classes by using scope so you don't have to worry close/dispose.
Lastly, For your question, you can use WHERE 1=1 then append any conditions you need.
Take your code as instance.
string connString = #"data source=ABC; database=XYZ; user id=sa; password=1234;";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string query = "SELECT * FROM EntryDatabase WHERE 1=1";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
if (Agree_type_srch.SelectedValue != null)
{
query += " AND Agree_type = #agree_type";
cmd.Parameters.AddWithValue("agree_type", Agree_type_srch.SelectedValue);
}
if (Status_srch.SelectedValue != null)
{
query += " AND Curnt_St = #curnt_st";
cmd.Parameters.AddWithValue("curnt_st", Status_srch.SelectedValue);
}
cmd.CommandText = query;
using (SqlDataAdapter sqldatad = new SqlDataAdapter())
{
DataSet ds = new DataSet();
sqldatad.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sqldatad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}

Related

Cascading for multiple selection of checkbox list

I want to retrieve data from oracle data base for one Checkbox list to another checkbox List for multiple selection in asp.net.
But unfortunately i am getting same ID again again while debugging.
Please help me Where i am doing mistake.
Is there any another easy approach on same.
I want something like : "Select d.depot_code, d.depot_description from table where d.depot in (depot_code from another Checkbox List) " [with comma separated ID]
CODE:
ddlregion Binding code:
public void BindRegion()
{
OracleCommand Cmd = new OracleCommand("select * from regions", con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlregion.DataSource = ds;
ddlregion.DataTextField = "REGION_DESC";
ddlregion.DataValueField = "REGION_CODE";
ddlregion.DataBind();
}
protected void ddlregion_SelectedIndexChanged(object sender, EventArgs e)
{
ddlDepot.Items.Clear();
ddlDepot.Items.Add(new ListItem("--Select Depot--", ""));
for (int i = 0; i < ddlregion.Items.Count; i++)
{
if (ddlregion.Items[i].Selected == true)
{
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr, depots d where r.region_code = sr.region_code and sr.sub_region_code = d.sub_region_code and active = 'Y' and d.depot_code = " + ddlregion.SelectedItem.Value + "";
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();
}
}
}
Thanks
Looking at your code again it doesn't look like you need to loop through your region dropdown list. In your ddlRegion_indexchanged just go ahead and bind your ddlDepot drop down and pass it the ddlregion.SelectedValue. So all you need is below, the ddlDepot will bind accordingly when you change the Region because you pass it the selected value every time.
string str = "select d.depot_code, d.depot_description from regions r, sub_regions sr, depots d where r.region_code = sr.region_code and sr.sub_region_code = d.sub_region_code and active = 'Y' and d.depot_code = " + ddlregion.SelectedValue + "";
OracleCommand Cmd = new OracleCommand(str, con);
Cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = Cmd;
da.Fill(ds);
ddlDepot.DataSource = ds;
ddlDepot.DataTextField = "DEPOT_DESCRIPTION";
ddlDepot.DataValueField = "DEPOT_CODE";
ddlDepot.DataBind();

i got an da.Fill(ds) error for my shopping card project in asp.net c#

public partial class AddToCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("ProductID");
dt.Columns.Add("ProductName");
dt.Columns.Add("Price");
dt.Columns.Add("ProductImage");
dt.Columns.Add("Cost");
dt.Columns.Add("TotalCost");
if (Request.QueryString["id"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=True";
SqlConnection scon = new SqlConnection(mycon);
String myquery = "select * from productdetail where ProductID=" + Request.QueryString["id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["ProductID"] = ds.Tables[0].Rows[0]["ProductID"].ToString();
dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
dr["ProductImage"] = ds.Tables[0].Rows[0]["ProductImage"].ToString();
dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
else
{
dt = (DataTable)Session["buyitems"];
int sr;
sr = dt.Rows.Count;
dr = dt.NewRow();
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=True";
SqlConnection scon = new SqlConnection(mycon);
String myquery = "select * from productdetail where ProductID=" + Request.QueryString["id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = sr + 1;
dr["ProductID"] = ds.Tables[0].Rows[0]["ProductID"].ToString();
dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
dr["ProductImage"] = ds.Tables[0].Rows[0]["ProductImage"].ToString();
dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
}
else
{
dt = (DataTable)Session["buyitems"];
GridView1.DataSource = dt;
GridView1.DataBind();
Update your connection string like below. You are missing to specify whether you want to use Windows Authentication or User Id & Password.
For Windows Authentication use Integrated Security=SSPI as below :
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=SSPI";
For Authentication with User Id & Password add User Id & Password as below. Use original user id and password. I have taken sa for example. :
String mycon = "Data Source=DESKTOP-8C66I6S/SQLEXPRESS;Initial Catalog=haritiShopping;Integrated Security=True;user id=sa;password=sa";
Also you need to open connection with
SqlConnection scon = new SqlConnection(mycon);
scon.Open(); //Open connection
P.S. It is always recommended to Close connection too. Add scon.Open(); after da.Fill(ds); line. Why always close Database connection?
.
da.Fill(ds);
scon.Close(); //Close connection

Must declare the scalar variable "#Format"

if (CheckBox1.Checked==false)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand("insert into CallCenter..Loy_DispMstr (CallType, SUBFormat, Disposition, SubDisposition) values (#CallType, #Format, #Disposition, #SubDisposition)", con);
cmd.Parameters.AddWithValue("CallType" , SqlDbType.VarChar).Value = ddlCalltype.SelectedItem.Value;
cmd.Parameters.AddWithValue("SUBFormat", SqlDbType.VarChar).Value = ddlFormat.SelectedItem.Value;
cmd.Parameters.AddWithValue("Disposition", SqlDbType.VarChar).Value = ddlDisp.SelectedItem.Value;
cmd.Parameters.AddWithValue("SubDisposition", SqlDbType.VarChar).Value = ddlSubdisp.SelectedItem.Value;
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
}
else if(flag==0 && CheckBox1.Checked==true)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand("insert into CallCenter..Loy_DispMstr (CallType, SUBFormat,Disposition, SubDisposition) values (#CallType, #Format,#Disposition, #SubDisposition)", con);
cmd.Parameters.AddWithValue("CallType", SqlDbType.VarChar).Value= ddlCalltype.Text;
cmd.Parameters.AddWithValue("SUBFormat", SqlDbType.VarChar).Value= ddlFormat.Text;
cmd.Parameters.AddWithValue("Disposition", SqlDbType.VarChar).Value= TextBox1.Text;
cmd.Parameters.AddWithValue("SubDisposition", SqlDbType.VarChar).Value= TextBox2.Text;
con.Open();
int i = cmd.ExecuteNonQuery();//error on this
con.Close();
}
}
the error is on the executenonquery
the error is on the executenonquery
the error is on the executenonquery
the error is on the executenonquery
Try this it will work for you :
if (CheckBox1.Checked == false)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand("insert into CallCenter..Loy_DispMstr (CallType, SUBFormat, Disposition, SubDisposition) values (#CallType, #Format, #Disposition, #SubDisposition)", con);
cmd.Parameters.Add("#CallType", ddlCalltype.SelectedItem.Value);
cmd.Parameters.Add("#Format", ddlFormat.SelectedItem.Value);
cmd.Parameters.Add("#Disposition", ddlDisp.SelectedItem.Value);
cmd.Parameters.Add("#SubDisposition", ddlSubdisp.SelectedItem.Value);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
Label2.Text = " Your data is been saved in the database";
Label2.ForeColor = System.Drawing.Color.ForestGreen;
}
else if (flag == 0 && CheckBox1.Checked == true)
{
String strConnString = ConfigurationManager.ConnectionStrings["CallcenterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand("insert into CallCenter..Loy_DispMstr (CallType, SUBFormat,Disposition, SubDisposition) values (#CallType, #Format,#Disposition, #SubDisposition)", con);
cmd.Parameters.Add("#CallType", ddlCalltype.Text);
cmd.Parameters.Add("#Format", ddlFormat.Text);
cmd.Parameters.Add("#Disposition", TextBox1.Text);
cmd.Parameters.Add("#SubDisposition", TextBox2.Text);
con.Open();
int i = cmd.ExecuteNonQuery();//error on this
con.Close();
}

i want code for Autocomplete Textbox Using Database Return Value in c#.net

private void txtBoxSearch_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection("connectionn string");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
string searchFor = "%" + txtBoxSearch.Text + "%";
com.CommandText = "select cust_nm from Customer_Info where (cust_nm LIKE ' % " + searchFor + " %') ";
con.Open();
cmd.Parameters.AddWithValue("#name", searchFor);
SqlDataReader rea = cmd.ExecuteReader();
if (rea.HasRows == true)
{
while (rea.Read())
namecollection.Add(rea["name"].ToString());
}
rea.Close();
txtBoxSearch.AutoCompleteMode = AutoCompleteMode.Suggest;
txtBoxSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtBoxSearch.AutoCompleteCustomSource = namecollection;
}
i want textbox which is act as a search option
A few problems here
You set the CommandText on com but execute cmd
You set % both on the variable and on the CommandText
You add a parameter but you don't have the parameter in the CommandText

What is wrong with my query in asp.net?

I am trying to fill a gridview by taking data from multiple tables. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "SELECT RegisterTable.CourseCode,
RegisterTable.courseNumber,
RegisterTable.Term,RegisterTable.Grade,
CourseTable.CourseName,
CourseTable.Level,
CourseTable.Credit
FROM RegisterTable,CourseTable
WHERE StudentID='" + MyGlobals.currentID + "' and
RegisterTable.CourseCode=CourseTable.CourseCode and
RegisterTable.CourseNumber=CourseTable.CourseNumber and
RegisterTable.Term=CourseTable.Term";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
GridView1.DataSource = tab;
GridView1.DataBind();
}
This gives an error saying that "Incorrect syntax near the keyword 'where'." Can anyone help me with this? Thanks
EDIT:
Ignore the string's lack of concatenation. It was all on one line and you had to scroll for a mile to see it all. They just made it easier to see.
Have you tried re-writing your query (so it's not using a cross-join)?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataAdapter adap = null;
string query = string.Empty();
DataSet ds = null;
DataTable tab = null;
con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
query = "SELECT RegisterTable.CourseCode, RegisterTable.CourseNumber, RegisterTable.Term, RegisterTable.Grade, CourseTable.CourseName, CourseTable.Level, CourseTable.Credit FROM RegisterTable INNER JOIN CourseTable ON RegisterTable.CourseCode = CourseTable.CourseCode AND RegisterTable.CourseNumber = CourseTable.CourseNumber AND RegisterTable.Term = CourseTable.Term WHERE StudentID = #StudentID;";
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("StudentID", SqlDbType.VarChar, 50).Value = MyGlobals.currentID;
ds = new DataSet();
adap = new SqlDataAdapter(cmd);
adap.Fill(ds);
if (ds.Tables.Count > 0) {
tab = ds.Tables(0);
}
GridView1.DataSource = tab;
GridView1.DataBind();
}

Resources