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

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.

Related

System.Data.SqlClient.SqlException: 'Invalid column name 'P1000'.'

Can anybody help me? Why am I getting this error?
If I remove the 'P' from the prod_id which left only number, it can work but if I add alphabet, it says "Invalid column name".
I already added .ToString() to it, but why it still can't take varchar and only take int.
Here is my code
public partial class AddtoCart : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(Global.cs);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
// Adding product to Gridview
Session["addproduct"] = "false";
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("Id");
dt.Columns.Add("Pname");
dt.Columns.Add("Pimage");
dt.Columns.Add("Pprice");
dt.Columns.Add("Pquantity");
dt.Columns.Add("Ptotal");
if (Request.QueryString["Id"] != null)
{
if (Session["buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
else
{
dt = (DataTable)Session["buyitems"];
int sr;
sr = dt.Rows.Count;
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["id"], conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = sr + 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
}
else
{
dt = (DataTable)Session["buyitems"];
GridView1.DataSource = dt;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
}
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Button3.Enabled = false;
Button1.Enabled = false;
}
else
{
Button3.Enabled = true;
Button1.Enabled = true;
}
}
// 2.Calculating Final Price
public int grandtotal()
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
int nrow = dt.Rows.Count;
int i = 0;
int totalprice = 0;
while (i < nrow)
{
totalprice = totalprice + Convert.ToInt32(dt.Rows[i]["Ptotal"].ToString());
i = i + 1;
}
return totalprice;
}
// 4. Deleting Row From Cart
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int sr;
int sr1;
string qdata;
string dtdata;
sr = Convert.ToInt32(dt.Rows[i]["sno"].ToString());
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
qdata = cell.Text;
dtdata = sr.ToString();
sr1 = Convert.ToInt32(qdata);
TableCell prID = GridView1.Rows[e.RowIndex].Cells[1];
if (sr == sr1)
{
dt.Rows[i].Delete();
dt.AcceptChanges();
conn.Open();
SqlCommand cmd = new SqlCommand("Delete top (1) from Cart where product_id='" + prID.Text + "' and username= '" + Session["username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Item Has Been Deleted From Shopping Cart
break;
}
}
// 5. Setting SNo. after deleting Row item from cart
for (int i = 1; i <= dt.Rows.Count; i++)
{
dt.Rows[i - 1]["sno"] = i;
dt.AcceptChanges();
}
Session["buyitems"] = dt;
Response.Redirect("AddtoCart.aspx");
}
// 6. Button Click
protected void Button1_Click(object sender, EventArgs e)
{
bool isTrue = false;
DataTable dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
//SqlConnection conn = new SqlConnection(Global.cs);
//conn.Open();
//SqlCommand cmd = new SqlCommand("insert into Cart(sno,product_id,product_name,product_price,product_quantity,username) values('" + dt.Rows[i]["sno"] + "','" + dt.Rows[i]["Id"] + "','" + dt.Rows[i]["Pname"] + "','" + dt.Rows[i]["Pprice"] + "','" + dt.Rows[i]["Pquantity"] + "','" + Session["Username"] + "')", conn);
//cmd.ExecuteNonQuery();
//conn.Close();
int pId = Convert.ToInt16(dt.Rows[i]["Id"]);
int pQuantity = Convert.ToInt16(dt.Rows[i]["Pquantity"]);
SqlDataAdapter sda = new SqlDataAdapter("Select stock_count, prod_name from Product2 where prod_id='" + pId + "' ", conn);
DataTable dtble = new DataTable();
sda.Fill(dtble);
int quantity = Convert.ToInt16(dtble.Rows[0][0]);
if(quantity == 0)
{
string pName = dtble.Rows[0][1].ToString();
string msg = "" + pName + " is not in Stock";
Response.Write("<script>alert('" + msg + "');</script>");
isTrue = false;
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Response.Write("<script>alert('Your Cart is Empty. You cannot place an Order');</script>");
}
else
{
if (isTrue == true)
{
Response.Redirect("Checkout2.aspx");
}
}
// If Session is Null Redirecting to login else Placing the order
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
else
{
Response.Redirect("Checkout2.aspx");
}
}
public void clearCart()
{
conn.Open();
SqlCommand cmd = new SqlCommand("Delete from Cart where username='" + Session["Username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("AddtoCart.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["buyitems"] = null;
clearCart();
}
}
This is the database table
CREATE TABLE [dbo].[Product2]
(
[prod_id] VARCHAR(6) NOT NULL,
[prod_name] VARCHAR(50) NOT NULL,
[prod_price] FLOAT(53) NOT NULL,
[prod_desc] VARCHAR(120) NOT NULL,
[prod_img] NVARCHAR(MAX) NOT NULL,
[prod_cat] VARCHAR(6) NOT NULL,
[stock_count] INT NULL,
[weight] DECIMAL(9, 2) NULL,
[width] DECIMAL(9, 2) NULL,
[length] DECIMAL(9, 2) NULL,
[height] DECIMAL(9, 2) NULL,
[shipping_fee] DECIMAL(9, 2) NOT NULL,
[created_at] DATETIME NOT NULL,
[updated_at] DATETIME NULL,
[prod_status] NVARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([prod_id] ASC),
CONSTRAINT [FK_Product2_ToTable]
FOREIGN KEY ([prod_cat]) REFERENCES [dbo].[Category] ([cat_id])
);
The way you pass the query could lead to SQL Injection.
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
I expect the final query you want to achieve is
select * from Product2 where prod_id=`P100`
But after revise your code if you do concatenate with 'P' in your query, you will get:
select * from Product2 where prod_id=P100
In which this will return result:
Invalid column name 'P100'
String concatenation into query is dangerous that possible break your query.
You need to create a SqlCommand variable and pass it to the SqlDataAdapter.
And also use SqlParameter to pass the parameter value.
SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
After create and initialize SqlCommand, then you pass it into SqlDataAdpater as below
SqlDataAdapter da = new SqlDataAdapter(cmd);
Additional recommendation:
Use using block for your SqlConnection, SqlCommand and SqlDataAdapter as these (implemented with IDisposable interface) will automatically dispose the resources once the process is ended or exception is triggered.
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(Global.cs))
{
using (SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con))
{
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
Updated answer with credited to #Tim Schmelter's suggestion
For Using declarations in C#8.0, you are not required to add scope for the using block.
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
DataSet ds = new DataSet();
using SqlConnection conn = new SqlConnection(Global.cs);
using SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

How to update 2 tables in c#

I have 2 tables
tbl_employer(Emp_num,Designation,Fname,Lname,Phone_no)
tbl_system_users(Emp_num,User_name,Password)
those two tables are filled by using one c# form(employer.cs).Only few employers have permission to access the system called system users. there are 2 text boxes for username and password in employer.cs. username and password text box should not null to save data to tbl_system_users and if both text boxes are null, it means they are only employers and not system users.
Emp_num of tbl_employer is auto increment field and a foreign key to tbl_system_users.
how can I update a employer detail?
public void update_employers(DTOUsers Users)
{
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "UPDATE tbl_employer SET Designation = '" + Users.Designation
+ "',,Employer_first_name = '" + Users.EmpFirstName + "',Employer_last_name = '"
+ Users.EmpLastName + "',, Phone_Num = '" + Users.PhoneNum + "' WHERE Emp_Num ='" + Users.EmpNum + "'";
con.Open();
cmd.ExecuteNonQuery();
if (Users.Password != "" && Users.UserName != "")
{
cmd.CommandText = "UPDATE tbl_system_users set User_name='" + Users.UserName + "',Password='" + Users.Password + "' where Emp_Num ='" + Users.EmpNum + "'";
cmd.ExecuteNonQuery();
}
con.Close();
in employer.cs
private void btn_update_Click(object sender, EventArgs e)
{
string emp_num = txt_emp_num.Text;
string designation = cmb_designation.Text;
string fname = txt_emp_fname.Text;
string lname = txt_emp_lname.Text;
string user_name = txt_user_name.Text;
string pw = txt_pw.Text;
string phno = txt_phn_num.Text;
DTOUsers emp = new DTOUsers();
emp.EmpNum = Convert.ToInt16(emp_num);
emp.Designation = designation;
emp.EmpFirstName = fname;
emp.EmpLastName = lname;
emp.UserName = user_name;
emp.Password = strh.Encrypt(pw);
emp.PhoneNum = phno;
dbh.update_employers(emp);
}
public void update_employers(DTOUsers Users)
{
bool firstStep = true;
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(con);
cmd.CommandText = "UPDATE tbl_employer SET Designation = #Designation,Employer_first_name = #EmpFirstName,Employer_last_name = #EmpLastName,Phone_Num = #PhoneNum WHERE Emp_Num = #PhoneNum";
//SqlDbType.VarChar Adjust according to the database values
cmd.Parameters.Add("#Designation", SqlDbType.VarChar, 30).Value = Users.Designation;
cmd.Parameters.Add("#EmpFirstName", SqlDbType.VarChar, 30).Value = Users.EmpFirstName;
cmd.Parameters.Add("#EmpLastName", SqlDbType.VarChar, 30).Value = Users.EmpLastName;
cmd.Parameters.Add("#PhoneNum", SqlDbType.VarChar, 30).Value = Users.PhoneNum;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
firstStep = false;
}
if (firstStep)
{
if (!string.IsNullOrEmpty(Users.Password) && !string.IsNullOrEmpty(Users.UserName))
{
cmd = new SqlCommand(con);
cmd.CommandText = "UPDATE tbl_system_users set User_name = #UserName,Password = #Password where Emp_Num = #PhoneNum";
cmd.Parameters.Add("#UserName", SqlDbType.VarChar, 30).Value = Users.UserName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 30).Value = Users.Password;
cmd.Parameters.Add("#PhoneNum", SqlDbType.VarChar, 30).Value = Users.PhoneNum;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
con.Close();
}
}
}
}

"There is no row at position 0 how to fix it"

During find data between two days, getting error "there is no row at position 0"
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["Demo"].ConnectionString.ToString());
string str = "select * from sample where name='" + Session["name"] + "' and date between '" + txtfirstdate.Text + "' and '" + txtenddate.Text + "'";
MySqlCommand cmd = new MySqlCommand(str, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataSet set = new DataSet();
connection.Open();
adapter.Fill(set);
connection.Close();
//var table = set.Tables[0];
if (set != null)
{
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}
Read the Error Message. Your result set table has no rows.
Replace u r if Condition.
if (set.Tables[0].Rows.Count > 0) {
lblname.Text = set.Tables[0].Rows[0]["name"].ToString();
lbldate.Text = set.Tables[0].Rows[0]["date"].ToString();
}

How to search over whole cities in combobox

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

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.

Categories

Resources