Advance search using dropdown list C# - c#

I an doing an advance search code .. I have 6 drop-down lists , the user can choose one or more value from one or all the drop downs or choose the "-" value which means no value selected .. My code is working and the result is the union of all the values .. how can I find only the intersect ?
I mean if I choose (Asia) from the first drop-down and (Arabic) from the second ,, my result is all the countries in Asia and all the countries that have Arabic language..
how can I have only the Asian countries that talks Arabic >> the intersect ?
if (!Class1.Search_Continent.Equals("-"))//DropDownList1.SelectedValue.ToString();
{
sunc.conn.Open();
SqlCommand cmd1 = new SqlCommand("Select Country_name FROM Country WHERE Continent_name='" + DropDownList1.SelectedValue + "'", sunc.conn);
SqlDataReader dr1;
dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{DropDownList9.Items.Add(dr1["Country_name"].ToString());}
sunc.conn.Close();
if (!Class1.Search_Country.Equals("-"))//DropDownList2.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
sunc.conn.Open();
SqlCommand cmd2 = new SqlCommand("Select Country_name FROM Country WHERE Country_name='" + DropDownList2.SelectedValue + "'", sunc.conn);
SqlDataReader dr2;
dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{DropDownList9.Items.Add(dr2["Country_name"].ToString());}
sunc.conn.Close();
if (!Class1.Search_City.Equals("-"))//DropDownList3.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
sunc.conn.Open();
SqlCommand cmd3 = new SqlCommand("Select Country_name FROM City WHERE City_name='" + DropDownList3.SelectedValue + "'", sunc.conn);
SqlDataReader dr3;
dr3 = cmd3.ExecuteReader();
while (dr3.Read())
{
DropDownList9.Items.Add(dr3["Country_name"].ToString());
}
//dr3.Close();
//conn3.Close();
sunc.conn.Close();
if (!Class1.Search_Religion.Equals("-"))//DropDownList4.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
//SqlConnection conn4 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
//conn4.Open();
sunc.conn.Open();
SqlCommand cmd4 = new SqlCommand("Select Country_name FROM Religion WHERE Religion_name='" + DropDownList4.SelectedValue + "'", sunc.conn);
SqlDataReader dr4;
dr4 = cmd4.ExecuteReader();
while (dr4.Read())
{
DropDownList9.Items.Add(dr4["Country_name"].ToString());
}
//dr4.Close();
//conn4.Close();
sunc.conn.Close();
if (!Class1.Search_Type.Equals("-"))//DropDownList5.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
//SqlConnection conn5 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
//conn5.Open();
sunc.conn.Open();
SqlCommand cmd5 = new SqlCommand("Select Country_name FROM Country WHERE Type_of_government='" + DropDownList5.SelectedValue + "'", sunc.conn);
SqlDataReader dr5;
dr5 = cmd5.ExecuteReader();
while (dr5.Read())
{
DropDownList9.Items.Add(dr5["Country_name"].ToString());
}
//dr5.Close();
//conn5.Close();
sunc.conn.Close();
if (!Class1.Search_Language.Equals("-"))//DropDownList6.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
//SqlConnection conn6 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
//conn6.Open();
sunc.conn.Open();
SqlCommand cmd6 = new SqlCommand("Select Country_name FROM Language WHERE Language_name='" + DropDownList6.SelectedValue + "'", sunc.conn);
SqlDataReader dr6;
dr6 = cmd6.ExecuteReader();
while (dr6.Read())
{
DropDownList9.Items.Add(dr6["Country_name"].ToString());
}
//dr6.Close();
//conn6.Close();
sunc.conn.Close();
if (DropDownList1.SelectedValue.Equals("-") && DropDownList2.SelectedValue.Equals("-") &&
DropDownList3.SelectedValue.Equals("-") && DropDownList4.SelectedValue.Equals("-") &&
DropDownList5.SelectedValue.Equals("-") && DropDownList6.SelectedValue.Equals("-"))
{
Button2.Enabled = false;
Label1.Text = "you have to choose from the dropdown list";
}
else if (DropDownList9.SelectedValue.Equals("-"))
{
Button2.Enabled = false;
Label1.Text = "No result ";
}
}
}
}
}
}
}

I would alter your code so that it creates one query based on the different options, then returns just the result of that query.
For example:
string query = "Select Country_name FROM Country WHERE Continent_name='" + DropDownList1.SelectedValue + "'";
if (!Class1.Search_Country.Equals("-"))
query+= " and Country_name='" + DropDownList2.SelectedValue + "'";
SqlCommand cmd1 = new SqlCommand(query, sunc.conn);

Generally you want to do this in a single query like:
SELECT Country_Name
FROM Country C
INNER JOIN City CTY on (CTY.Country_Name = C.Country_Name)
INNER JOIN Religion R on (R.Country_Name = C.Country_Name
WHERE ((#City ='') or (CTY.City_Name = #City))
AND ((#Religion ='') or (R.Religion_Name = #Religion))
AND ((#Government = '') or (C.Type_of_Government = #Government))
You would then pass #City, #Religion and #Government as parameters to the query. If any individual parameter is passed in then the WHERE clause would filter on it; or ignore if that parameter was blank.

You have to modify the query something like below.
SqlCommand cmd1 = new SqlCommand("Select Country_name FROM Country WHERE (Continent_name='" + DropDownList1.SelectedValue + "' or Continent_name=Continent_name) AND (Country_name='" + DropDownList2.SelectedValue + "' OR Country_name=Country_name) AND (City_name='" + DropDownList3.SelectedValue + "' OR City_name=City_name) AND (Religion_name='" + DropDownList4.SelectedValue + "' OR Religion_name=Religion_name) AND (Type_of_government='" + DropDownList5.SelectedValue + "' OR Type_of_government=Type_of_government) AND (Language_name='" + DropDownList6.SelectedValue + "' OR Language_name=Language_name)", sunc.conn);
Hope this Helps!!

Related

Update SQL Server table columns with button click from gridview fields

I have a gridview that displays all the fields from my table.
My problem is that I need to update my SQL Server table when I click the save button (onclick) because I added a new field that generates a unique ID to every Item I have in my table. And It will add the generated id to the database table whenever I click the save button.
I have tried this
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text +
"' , [prno], [itemaname], [specification], [qty], [uomid], [expenseid],
[statusid], [userid], [inserteddate], [withquotation], [potempid] WHERE
idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
But I get an error
Here is my complete code:
public void SaveTogrdPOTemp()
{
SqlConnection ConnString = new SqlConnection(ConfigurationManager.ConnectionStrings["MUCS2.0ConnectionString"].ConnectionString);
string strSql = string.Empty;
pextid = "TPID";
using (SqlCommand cmd = new SqlCommand("SELECT * FROM GenIDGen WHERE extid = '" + pextid + "'"))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = ConnString;
ConnString.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
var extid = sdr["extid"].ToString().Trim();
var genID = sdr["generatedid"].ToString().Trim();
var gentr = sdr["generator"].ToString();
var potempoid = extid + genID;
ConnString.Close();
}
}
strSql = "UPDATE [dbo].[GenIDGen] SET [generator] = generator + 1
WHERE extid = '" + pextid + "' ";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text + "' WHERE idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
}
For the generating of ID and the updating of the gridview. Thank you!

ASP.NET C# - Edit Account Page INSERT and UPDATE data

I'm not a strong coder and quite new to C#. I am having problems with the edit account page of the website that I am trying to create. I am trying to update and insert data into the database and they don't seem to work.
Here's my code:
public partial class EditAccount : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
private readonly object MessageBox;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlCommand com;
string str;
conn.Open();
str = "SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, CardDetails.CardDetailsID, CardDetails.NameOnCard, CardDetails.NameOfCard, CardDetails.CardNumber, CardDetails.CardExpiryDate, CardDetails.CVV, AddressType.AddressTypeDescription, Member.MemberID, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address FULL JOIN AddressType ON Address.AddressTypeID = AddressType.AddressTypeID FULL JOIN Member ON AddressType.MemberID = Member.MemberID FULL JOIN CardDetails ON Member.MemberID = CardDetails.MemberID WHERE Member.Email = '" + Session["Email"] + "'";
com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
TxtEName.Text = reader["MemberName"].ToString();
LblEUser.Text = reader["Username"].ToString();
TxtEEmail.Text = reader["Email"].ToString();
TxtEPhone.Text = reader["Phone"].ToString();
TxtEType.Text = reader["AddressTypeDescription"].ToString();
TxtEHouse.Text = reader["HouseNumber"].ToString();
TxtEA1.Text = reader["AddressLine1"].ToString();
TxtEA2.Text = reader["AddressLine2"].ToString();
TxtECity.Text = reader["City"].ToString();
TxtEPostcode.Text = reader["PostCode"].ToString();
TxtENameOf.Text = reader["NameOfCard"].ToString();
TxtENameOn.Text = reader["NameOnCard"].ToString();
TxtECardNo.Text = reader["CardNumber"].ToString();
TxtEExpDate.Text = reader["CardExpiryDate"].ToString();
TxtECVV.Text = reader["CVV"].ToString();
reader.Close();
conn.Close();
}
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
conn.Open();
SqlDataAdapter str = new SqlDataAdapter ("SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, CardDetails.NameOnCard, CardDetails.NameOfCard, CardDetails.CardNumber, CardDetails.CardExpiryDate, CardDetails.CVV, AddressType.AddressTypeDescription, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address FULL JOIN AddressType ON Address.AddressTypeID = AddressType.AddressTypeID FULL JOIN Member ON AddressType.MemberID = Member.MemberID FULL JOIN CardDetails ON Member.MemberID = CardDetails.MemberID WHERE Member.Email = '" + Session["Email"] + "'",conn);
DataSet ds = new DataSet();
str.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
SqlCommand updateCommand = new SqlCommand("UPDATE Member SET MemberName = '" + TxtEName.Text + "', Email = '" + TxtEEmail.Text + "', Phone = '" + TxtEPhone.Text + "'", conn);
SqlCommand updateCommand1 = new SqlCommand("UPDATE Address SET HouseNumber ='" + TxtEHouse.Text + "', AddressLine1 = '" + TxtEA1.Text + "', AddressLine2 = '" + TxtEA2.Text + "', City = '" + TxtECity.Text + "',PostCode = '" + TxtEPostcode.Text + "'", conn);
SqlCommand updateCommand2 = new SqlCommand("UPDATE AddressType SET AddressTypeDescription = '" + TxtEType.Text + "'", conn);
SqlCommand updateCommand3 = new SqlCommand("UPDATE CardDetails SET NameOnCard = '" + TxtENameOn.Text + "', NameOfCard = '" + TxtENameOf.Text + "', CardNumber = '" + TxtECardNo.Text + "', CardExpiryDate = '" + TxtEExpDate.Text + "', CVV = '" + TxtECVV.Text + "'", conn);
updateCommand.ExecuteNonQuery();
updateCommand1.ExecuteNonQuery();
updateCommand2.ExecuteNonQuery();
updateCommand3.ExecuteNonQuery();
Response.Write("<script>alert('Changes saved')</script>");
}
else
{
SqlCommand insertCommand = new SqlCommand("INSERT INTO AddressType (AddressTypeDescription) VALUES (#AddressTypeDescription)", conn);
insertCommand.Parameters.AddWithValue("#AddressTypeDescription", TxtEType.Text);
insertCommand.ExecuteNonQuery();
SqlCommand insertCommand1 = new SqlCommand("INSERT INTO Address (HouseNumber, AddressLine1, AddressLine2, City, PostCode) VALUES (#HouseNumber, #AddressLine1, #AddressLine2, #City, #PostCode)", conn);
insertCommand1.Parameters.AddWithValue("#HouseNumber", TxtEHouse.Text);
insertCommand1.Parameters.AddWithValue("#AddressLine1", TxtEA1.Text);
insertCommand1.Parameters.AddWithValue("#AddressLine2", TxtEA2.Text);
insertCommand1.Parameters.AddWithValue("#City", TxtECity.Text);
insertCommand1.Parameters.AddWithValue("#PostCode", TxtEPostcode.Text);
insertCommand1.ExecuteNonQuery();
SqlCommand insertCommand2 = new SqlCommand("INSERT INTO CardDetails (NameOnCard, NameOfCard, CardNumber, CardExpiryDate, CVV) VALUES (#NameOnCard, #NameOfCard, #CardNumber, #CardExpiryDate, #CVV)", conn);
insertCommand2.Parameters.AddWithValue("#NameOnCard", TxtENameOn.Text);
insertCommand2.Parameters.AddWithValue("#NameOfCard", TxtENameOf.Text);
insertCommand2.Parameters.AddWithValue("#CardNumber", TxtECardNo.Text);
insertCommand2.Parameters.AddWithValue("#CardExpiryDate", TxtEExpDate.Text);
insertCommand2.Parameters.AddWithValue("#CVV", TxtECVV.Text);
insertCommand2.ExecuteNonQuery();
Response.Write("<script>alert('Changes saved')</script>");
}
conn.Close();
}
}

syntax error (missing operator) in query expression

I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.

Another shorten SQL string? c#

Some may already be noticing this and I would like to confirm it, I am really inexperienced with complex SQL strings. I only know simple SELECT , INSERT , UPDATE and DELETE statements. And to achieve my purpose I often use 2 SELECT statements, like this one :
con.Open();
string cmdstr = "SELECT UNIQUE FROM recipeList WHERE `stock_ID` = '" + stockIDTxtbox.Text + "'";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuID = "";
while (dr.Read())
{
menuID = (dr["menu_ID"].ToString());
}
dr.Close();
con.Close();
con.Open();
string cmdstr = "SELECT `menu_name` FROM recipedb WHERE `menu_ID` = '" + menuID + "'";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuName = "";
while (dr.Read())
{
menuName = (dr["menu_name"].ToString());
this.listView1.Items.Add(new ListViewItem(new string[]{ menuName }))
}
dr.Close();
con.Close();
Any ideas how to shorten this? o.O
You may write an SQL as:
string queryString = "SELECT r2.menu_name "+
"FROM recipelist rl "+
"INNER JOIN recipedb r2 "+
"ON rl.menu_ID = r2.menu_ID "+
"WHERE r1.stock_ID = '" + stockIDTxtbox.Text + "'";
Haven't written SQL in a while but it should be a join, so something like the following:
select rdb.menu_name
from recipedb rdb,
recipelist rl
where rl.menu_ID = rdb.menu_ID and
rl.stock_ID = * insert your stockIDTxtbox.Text in here without the stars *
Here is a short one:
con.Open();
string cmdstr = "SELECT menu_name FROM recipedb WHERE menu_ID in (SELECT UNIQUE menu_id from recipeList WHERE stock_ID = '" + stockIDTxtbox.Text + "')";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuName = "";
while (dr.Read())
{
menuName = (dr["menu_name"].ToString());
this.listView1.Items.Add(new ListViewItem(new string[]{ menuName }))
}
dr.Close();
con.Close();

Shortening data access code... would this work?

I am querying for data, if the data does not exist, I insert it. if it does, I do something else:
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = '" + orderNo + "';", connection);
SqlDataReader checkHeadReader = checkHead.ExecuteReader(CommandBehavior.SingleRow);
if (!checkHeadReader.HasRows)
{
checkHeadReader.Close();
addHead.ExecuteNonQuery();
}
But I wonder if there's a shorter way to code this? would the code below work?
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = ' + orderNo + "';", connection);
if(checkHead.ExecuteReader(CommandBehavior.SingleRow).HasRows)
addHead.ExecuteNonQuery();
else //this order already exists
Server.Transfer(#"~/Views/Error.aspx");
ExecuteScalar is great for this, E.g.
using (SqlCommand cmdCheck = new SqlCommand("Select Count(*) From Table Where Order_No = '" + orderNo + "'", connection))
{
int nExists = (int)cmdCheck.ExecuteScalar();
if (nExists==0) addHead.ExecuteNonQuery();
}

Categories

Resources