How to search over whole cities in combobox - c#

I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox.
string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();

You could change the statement in case of "nothing selected"
if (ComboBox.Text == string.Empty)
{
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
Remarks:
use variable names like string sCity = "%"; instead of string c = "%";
use parameters for your sql statements where ( PER_ID = #Person) and cmd.Parameters.Add("#Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);

If I get you correctly, you don't want where clause on GOV_NAME_AR when combobox1 is not selected.
if( ComboBox.SelectedItem == null ) {
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}

You could do a check on the ComboBox.SelectedText like this:
if (comboBox1.SelectedText=="")
{
//SQL statement should not restrict on the c value
}
else
{
//Use your regular SQL query here.
}

Related

How To Get Records From Date To Date SQL Server

am going to explain it in pictures and Source Code
Front Design
Back-end Code
private void AddRecord(object sender, RoutedEventArgs e)
{
string date = datee.Text + " " + DateTime.Now.ToLongTimeString();
if (datee.Text == "" || cusname.SelectedValue == null || Vanda.SelectedValue == null || price.SelectedValue == null || bags.Text == "")
{
MessageBox.Show("please fill the data");
}
else
{
DataRowView dt = (DataRowView)Vanda.SelectedItem;
string vda = dt["vanda"].ToString();
DataRowView dt2 = (DataRowView)price.SelectedItem;
string data2 = dt2["price"].ToString();
decimal dta = Convert.ToDecimal(data2);
Int32 pricee = Convert.ToInt32(dta);
decimal bag = Convert.ToDecimal(bags.Text);
decimal credit = pricee * bag;
DataRowView cus = (DataRowView)cusname.SelectedItem;
string cusidd = cus["id"].ToString();
int cusid = Convert.ToInt16(cusidd);
con.Open();
SqlCommand cmd5 = new SqlCommand("SELECT price - retailprice FROM vanda where vanda = '" + vda + "' and price = '" + pricee + "'", con);
SqlDataReader reader = cmd5.ExecuteReader();
reader.Read();
string val = reader.GetValue(0).ToString();
decimal valu = Convert.ToDecimal(val);
Int32 profit = Convert.ToInt32(valu);
reader.Close();
SqlCommand cmd3 = new SqlCommand("insert into records (cusid,datee,description,vanda,price,bag,credit,debit,profit) values ('" + cusid + "','" + date + "','" + des.Text + "','" + vda + "','" + pricee + "','" + bags.Text + "','" + credit + "','','"+profit+"')", con);
cmd3.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
con.Close();
}
}
DataGrid Code
private void enddate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
if (startdate.Text == "")
{
MessageBox.Show("Please Select Starting Date");
}
else
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(" i need here Query ", con);
DataSet ds = new DataSet();
adapter.Fill(ds);
data.DataContext = ds.Tables[0];
}
}
SQL Server Database
i hope you will understand it clearly. now clear the bugs and improve my code/logic/query (^_^). bla bla bla bla bla bla bla bla bla bla bla
First, your SQL should be using named parameters to avoid SQL Injection Attacks:
select r.datee,c.name,r.description,r.vanda,r.price,r.bag,r.credit,r.debit
from records as r,
customer as c
where r.cusid = c.id
and c.name = #cname
and r.datee BETWEEN #startDate AND #endDate
When you create these variables, which you will pass into your query, format them as follows:
var startDate = DateTime.Parse(datee.Text).ToString("M/d/yyyy");
var endDate = DateTime.Now.ToString("M/d/yyyy") + " 23:59:59";
This will convert the date values to the format your database expects.
select r.datee,c.name,r.description,r.vanda,r.price,r.bag,r.credit,r.debit
from records r
JOIN customer c ON r.cusid = c.id
WHERE c.name = 'aizaz' AND DateColumn BETWEEN StartDate AND EndDATE
The database doesn't store the dates in any specific string format. A date is a date and it has no specific format. Formatting the output of a date is a UI thing.
You get the actual DateTime value of a DatePicker using the SelectedDate property. You should use pass these values as parameters to your command:
SqlCommand cmd = new SqlCommand("select r.datee,c.name,r.description,r.vanda,r.price,r.bag,r.credit,r.debit from records as r, customer as c where r.cusid = c.id and c.name = #cname and r.datee BETWEEN #startDate AND #endDate");
cmd.Parameters.AddWithValue("#startDate", datePicker1.SelectedDate.Value.Date);
cmd.Parameters.AddWithValue("#endDate", datePicker2.SelectedDate.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59));

Need to find ID number from database using string in c#

I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp
As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";

Parameters supplied for object which is not a function. If the parameters are intended as a table hint, a WITH keyword is required

I'm running Windows 7 and II7 and SQL server 2008 R2 . I have an aspx program and when I try to run it I get the following error
Parameters supplied for object 'users' which is not a function. If
the parameters are intended as a table hint, a WITH keyword is
required.
What I've coded is this :
public ArrayList GetGoodsList(string type, string goodsType, string user, string payType, bool flag)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Conn"].ToString());
DataSet ds = new DataSet();
sSql = "select count(*) from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sSql;
conn.Open();
int maxRow = Int32.Parse(cmd.ExecuteScalar().ToString());
sSql = "select * from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
cmd.CommandText = sSql;
SqlDataReader reader = cmd.ExecuteReader();
ArrayList gInfos = new ArrayList();
GoodsInfo gInfo;
for (int i = 0; i < maxRow; i++)
{
if (reader.Read())
{
gInfo = new GoodsInfo();
gInfo.G_ID = Int32.Parse(reader["G_ID"].ToString());
gInfo.G_Name = reader["G_Name"].ToString();
gInfo.Type = reader["Type"].ToString();
gInfo.GoodsType = reader["GoodsType"].ToString();
gInfos.Add(gInfo);
}
}
conn.Close();
return gInfos;
}
Any idea? Thanks!
Without giving away the answer, your issue in in your SELECT statement, sSql = ...
It's not the correct SQL syntax.
Have a read of this wikipedia article on the SELECT statement.

Update, Insert to sql .. There is already an open DataReader associated with

string[] stringList2 = new string[10];
if (VaildDataRow == true)
{
//Response.Write("<script>alert('2valid data row" + TbRow + "')</script>");
TbCol = 0;
TcCol = 1;
foreach (TableCell tc in tr.Cells)
{
#region //Load array with valid row text boxes' value
foreach (Control c1 in tc.Controls)
{
if (c1 is TextBox)
{
if (c1.ID.StartsWith("DataTbFld_"))
{
TextBox txt = (TextBox)t11.FindControl(c1.ID);
if (string.IsNullOrEmpty(txt.Text))
{
//Response.Write("<script>alert('txt#id ..not hidden..: " + txt.ID + " found data in textbox, rec is valid , will break')</script>");
txt.Text="Null";
}
stringList2[TbCol] = txt.Text.ToString();
//Response.Write("<script>alert('TbRow : " + TbRow + " TcCol : " + TcCol + " TbCol : " + TbCol + " txt.Text.ToString() : " + txt.Text.ToString() + "')</script>");
}
TbCol += 1;
}
}
#endregion//===
TcCol += 1;
}
Response.Write("<script>alert('TbRow : " + TbRow + "')</script>");
#region //if exist update else insert
Response.Write("<script>alert('InputDate = " + stringList2[6] +
" and Dept= " + stringList2[7] + " and DeptType= " + stringList2[8] +
" and DeptSubType= " + stringList2[9] + "')</script>");
con.Open();
cmd = new SqlCommand("SELECT * FROM MainDailyData WHERE Dept= '" + stringList2[7] + "' and DeptType = '" + stringList2[8] + "' and DeptSubType= '" + stringList2[9] + "'", con);
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
{
Response.Write("<script>alert('Found,Update')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.UpdateCommand = new SqlCommand("UPDATE MainDailyData SET Product1 = #Prod1, Product2 = #Prod2, Product3 = #Prod3, Product4 = #Prod4, Product5 = #Prod5, Product6 = #Prod6, InputDate = #InDate, Dept = #Dpt, DeptType = #DptType, DeptSubType = #DptSubType", con);
myda.UpdateCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.UpdateCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.UpdateCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.UpdateCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.UpdateCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.UpdateCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.UpdateCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.UpdateCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.UpdateCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.UpdateCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
//dr.Close();
//con.Open();
myda.UpdateCommand.ExecuteNonQuery();
}
else
{
Response.Write("<script>alert('not Found,Insert')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.InsertCommand = new SqlCommand("INSERT INTO MainDailyData (Product1,Product2,Product3,Product4,Product5,Product6,InputDate,Dept,DeptType,DeptSubType) VALUES(#Prod1,#Prod2,#Prod3,#Prod4,#Prod5,#Prod6,#InDate,#Dpt,#DptType,#DptSubType)", con);
myda.InsertCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.InsertCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.InsertCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.InsertCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.InsertCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.InsertCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.InsertCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.InsertCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.InsertCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.InsertCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
//dr.Close();
//con.Open();
myda.InsertCommand.ExecuteNonQuery();
}
con.Close();
#endregion
}
#endregion
TbRow += 1;
}
when excauting
myda.InsertCommand.ExecuteNonQuery();
or
myda.UpdateCommand.ExecuteNonQuery();
i got error msg
There is already an open DataReader associated with this Command which must be closed first
if I close dr the result will be messy. If it found record in row 2 of the table, it will insert record of row 1 from the table to the database
i tried to enable MultipleActiveResultSets="true", but i got a problem attribute is not allowed!
I want to check if record exist, update else ,insert. how to achieve this or how to correct my code?
after edition:
#region //if exist update else insert inserting code
//Response.Write("<script>alert('InputDate = " + stringList2[6] +
//" and Dept= " + stringList2[7] + " and DeptType= " + stringList2[8] +
//" and DeptSubType= " + stringList2[9] + "')</script>");
con.Open();
//cmd = new SqlCommand("SELECT 1 FROM MainDailyData WHERE Dept= '" + stringList2[7] +
// "' and DeptType = '" + stringList2[8] + "' and DeptSubType= '" + stringList2[9] + "'", con);
cmd = new SqlCommand("SELECT 1 FROM MainDailyData WHERE Dept= #dpt and DeptType = #dptType and DeptSubType= #DptSbType", con);
cmd.Parameters.AddWithValue("#dpt", stringList2[7]);
cmd.Parameters.AddWithValue("#dptType", stringList2[8]);
cmd.Parameters.AddWithValue("#DptSbType", stringList2[9]);
bool fRecordExists = false;
SqlDataReader dr = cmd.ExecuteReader();
//SqlDataReader dr = cmd.ExecuteScalar();
if (dr != null && dr.HasRows)
{
fRecordExists = true;
}
dr.Close();
dr.Dispose();
if (fRecordExists)
{
Response.Write("<script>alert('Found,Update')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.UpdateCommand = new SqlCommand("UPDATE MainDailyData SET Product1 = #Prod1, Product2 = #Prod2, Product3 = #Prod3, Product4 = #Prod4, Product5 = #Prod5, Product6 = #Prod6, InputDate = #InDate, Dept = #Dpt, DeptType = #DptType, DeptSubType = #DptSubType", con);
myda.UpdateCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.UpdateCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.UpdateCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.UpdateCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.UpdateCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.UpdateCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.UpdateCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.UpdateCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.UpdateCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.UpdateCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
myda.UpdateCommand.ExecuteNonQuery();
}
else
{
Response.Write("<script>alert('not Found,Insert')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.InsertCommand = new SqlCommand("INSERT INTO MainDailyData (Product1,Product2,Product3,Product4,Product5,Product6,InputDate,Dept,DeptType,DeptSubType) VALUES(#Prod1,#Prod2,#Prod3,#Prod4,#Prod5,#Prod6,#InDate,#Dpt,#DptType,#DptSubType)", con);
myda.InsertCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.InsertCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.InsertCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.InsertCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.InsertCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.InsertCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.InsertCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.InsertCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.InsertCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.InsertCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
myda.InsertCommand.ExecuteNonQuery();
}
con.Close();
#endregion
still the problem exist for updating or inserting the second row, if i fill 1st first record and leave the second empty, it will insert it to the db but will not eccept any inserting later to the second row, instead it will duplicate the 1st row record. interchangablly, for if i fill the the second row first. if i fill both if them # the begining it will insert them both but will not recognize the second record and will duplicate the first record?
Just close the dr immediately after you determine whether or not it has any results; you aren't using it for anything other than determining if the record exists or not, so this won't affect your logic at all.
Replace:
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
with:
bool fRecordExists = false;
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
{
fRecordExists = true;
}
dr.Close();
if (fRecordExists)
You should also change the select statement to a parameterized query to prevent SQL injection attacks and exceptions due to unexpected characters in the data.
Also, the select statement, if it isn't going to be used for anything other than existence verification, should just do SELECT 1 instead of SELECT * to prevent unneeded processing in both the database and application.
Finally, if your application data supports it (i.e. the select criteria will only select 1 record at the max), I would suggest using ExecuteScalar instead of ExecuteReader, which would eliminate your problem altogether.

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

Categories

Resources