Following is the code for the button but when I click the button, it does not forward me to the desired page. Is there something wrong with my DataReader loop?
{
SqlConnection connBadge = new SqlConnection("Data Source =localhost;" +
"Initial Catalog = BreastCancer; Integrated Security = SSPI");
connBadge.Open();
SqlCommand cmdfBadge = new SqlCommand("SELECT * FROM Products WHERE pid=1", connBadge);
SqlDataReader dr;
dr = cmdfBadge.ExecuteReader();
while (dr.Read())
{
String pName = dr["pName"].ToString();
String pPrice = dr["pPrice"].ToString();
int b = Convert.ToInt16(pPrice);
int a = Convert.ToInt16(ddQty1.SelectedValue.ToString());
int g = a * b;
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values('" + pName + "', '" + b + "', '" + a + "','" + g + "')";
SqlCommand cmdBadge = new SqlCommand(Badge, connBadge);
cmdBadge.ExecuteNonQuery();
}
dr.Close();
connBadge.Close();
Response.Redirect("Cart.aspx");
}
Use parameter and try sqldata adapter:
{
SqlConnection connBadge = new SqlConnection("Data Source =localhost;" +
"Initial Catalog = BreastCancer; Integrated Security = SSPI");
connBadge.Open();
SqlCommand cmdfBadge = new SqlCommand("SELECT * FROM Products WHERE pid='1'", connBadge);
var dSet = new DataSet();
var dt = new Datatable();
var da = new SqlDataAdapter(cmdfBadge);
da.Fill(dSet);
dt = dSet.Tables[0];
foreach(Datarow a in dt.Rows)
{
String pName = a["pName"].ToString();
String pPrice = a["pPrice"].ToString();
int b = Convert.ToInt16(pPrice);
int a = Convert.ToInt16(ddQty1.SelectedValue.ToString());
int g = a * b;
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values(#Name,#Price,#Quantity,#gPrice)";
SqlCommand cmdBadge = new SqlCommand(Badge, connBadge);
sqlCommand.Addwithvalue("#Name",pName);
sqlCommand.Addwithvalue("#Price",b)
sqlCommand.Addwithvalue("#Quantity",a)
sqlCommand.Addwithvalue("#gPrice",g)
cmdBadge.ExecuteNonQuery();
}
connBadge.Close();
Response.Redirect("Cart.aspx");
}
Regards
Wrap the code with a try/catch statement to see if any exceptions are thrown.
Verify your insert statement, I believe it will fail if the datatypes of your price, quantity and gprice are of type integer:
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values('" + pName + "', '" + b + "', '" + a + "','" + g + "')";
You should not wrap these in quotes, remove the quotes and try again.
String Badge = "INSERT into Cart (Name,Price,Quantity,gPrice) Values('" + pName + "', " + b + ", " + a + "," + g + ")";
Try to use descriptive variable names, the using statement and a try-catch statement, in the future.
Related
I am getting Unclosed quotation mark after the character string ''. and I have tried everything any help would be greatly appreciated.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sipConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string query = "select dealercode, dropdate, couponno from coupon where dealercode = '" + DEALERCODETextBox.Text + "' and dropdate = '" + DROPDATETextBox.Text + "' and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#totalrev", GRANDTOTALTextBox.Text);
cm.ExecuteNonQuery();
conn.Close();
In the last of your query string
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
replace +"','"; with "'";
Note: Your query string also lack of Parameters
You use paramters to add the values, but you don't use the parameters in the query:
string query = "select dealercode, dropdate, couponno from coupon where dealercode = #dealercode and dropdate =#dropdate and COUPONNO = #couponcount;";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#dealercode ", DEALERCODETextBox.Text);
cm.Parameters.AddWithValue("#dropdate ", DROPDATETextBox.Text);
Replace with this line:
string query = "select dealercode, dropdate, couponno
from coupon where dealercode = '" + DEALERCODETextBox.Text + "'
and dropdate = '" + DROPDATETextBox.Text + "'
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"'";
SqlCommand cm = new SqlCommand(query, conn);
i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here
I am assigning the value to the variable from the text box on the page during the pageupload event of AjaxFileUpload1.The problem is that, I am not getting the value from the text box to my variable even though no error throws.My variables are
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
Any idea why AjaxFileUpload1_UploadComplete is not able to read text box value
My cs Code is:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
Please help me
I spent some time last week investigating this question but in the end couldn't find an easy solution for this. The OP in that question solved it by storing values in the Session but for this to work you would still need to cause a postback at some stage.
There apparently was functionality planned for the AjaxFileUpload control to pass values in the Context Keys collections but this was never implemented. This question describes how to implement this yourself though.
I think I saw another question around the same topic and the OP solved it by changing to using the AsyncFileUpload control but I stand to be corrected...
i think you need to add !Page.IsPostBack to your code. like this
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if(!Page.IsPostBack)
{
string c = System.IO.Path.GetFileName(e.FileName);
string dpath = "~/Profile/Images/";
string scn = txtSCN.Text;
string line1 = txtLineitem.Text;
string aging1 = txtAging.Text;
AjaxFileUpload1.SaveAs(MapPath(Path.Combine(dpath,c)));
dpath = dpath + c;
string str1 = ConfigurationManager.ConnectionStrings["ProTracConnGMCH"].ConnectionString;
SqlConnection cn = new SqlConnection(str1);
cn.Open();
string sql = "Update tbNoquoteFollowupupdate set MailreceivedURL = '" + dpath + "', chkMailreceived = 1 , Buyername = '" + buyername + "' where scn = '" + scn + "' AND lineItem = '" + line1 + "' and Aging ='" + aging1 + "' ";
SqlCommand cmd = new SqlCommand(sql, cn);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// AjaxFileUpload1.SaveAs(Path.Combine(dpath, e.FileName));
//AjaxFileUpload1.SaveAs(MapPath(dpath));
}
cn.Close();
BindGridviewData1();
cn.Open();
string cmd2 = "Insert Into tbMulitmailsreived (scn, lineItem,followupdate, Aging,MailreceivedURL) Values ('" + scn + "', '" + line1 + "','" + DateTime.Now + "','" + aging1 + "','" + dpath + "')";
SqlCommand sqlCommand2 = new SqlCommand(cmd2, cn);
sqlCommand2.ExecuteNonQuery();
cn.Close();
}
}
i have a button that suppose to update data into the database.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
conn.Close();
}
but i get this error..
can someone help?
update =
i've changed my code to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
but the problem now is that , there's no update.
the iCount in the database is an INT , value is 0.
There is also no update for the viewtime and lastview.
where did i go wrong now?
change this:
cmdC.CommandText = "Update ComDet set iCount = '" + z + "', ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
to
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
you dont need the "'" apostrophe around it becuase its a number. That would definitely get you string not in correct format error
I would guess maybe the icount value is not a number, i would recommend using TryParse just in case. And that should keep this error from happening. What to do about a bad value getting returned by the query is another issue.
private void button4_Click(object sender, EventArgs e)
{
//need update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = 0;
if(Int32.TryParse(x,out y))
{
System.Diagnostics.Debug.WriteLine("iCount was an valid int32");
int z = y + 1;
//SqlCeCommand cmdC = conn.CreateCommand();
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
}
else
System.Diagnostics.Debug.WriteLine("iCount was NOT a valid int32, value: " + x);
conn.Close();
}
Have you checked the value of the 'x' variable? The exception informs that the value of X isn't a valid integer, so the FormatException is thrown.
I'm new to .net development
I'm trying to fetch the data from Facebook app,when update the query I'm getting the above error on update customer details
in 'cust_date' filed and i taken in cust_date datatype is DATETIME.
so how to convert this DATETIME format to 'MM/DD/YYYY HH:MM'
public void Customer(string Customerid)
{
var accessToken = "CAACEdEose0cBAMTINaTZCrm67pT6cO16KHsR3UNgOTZAGH03GHmhKozUOxEXYpL3ZB9pfbFWm4Oj2VMVy8xMf5vXMpFtY6LZm2Hej0WmrHPlwk7pWyibf9gXbCaDBoIih26nRqffAfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(Customerid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string fst_name = obj["first_name"].ToString();
string lst_name = obj["last_name"].ToString();
string link = obj["link"].ToString();
string[] splitlink = link.Split('/');
if (splitlink[3].StartsWith("profile"))
{
splitlink[3] =name.ToString();
link = splitlink[0] + '/' + splitlink[1] + '/' + splitlink[2] + '/' + splitlink[3];
}
string gender = obj["gender"].ToString();
string cust_updated_time = obj["updated_time"].ToString();
string abctime = cust_updated_time.Substring(0, cust_updated_time.ToString().Length - 3);
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy3 = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy3, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myOleConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy = "select * from fb_customer";
myOleConnection.Open();
SqlCommand myOleCommand = new SqlCommand(qy, myOleConnection);
myOleCommand.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,firstname,lastname,link,gender,cust_date,New) values('" + custid + "','" + name + "','" + fst_name + "','" + lst_name + "','" + link + "','" + gender + "','" + abctime + "','1')";
SqlDataReader myOleDataReader = myOleCommand.ExecuteReader();
myOleDataReader.Close();
myOleConnection.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = " UPDATE fb_customer set name='" + name + "',firstname='" + fst_name + "',lastname='" + lst_name + "',link='" + link + "',gender='" + gender + "',cust_date= '" + abctime + "' where customer_fb_id = '" + custid + "'";
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
public void IIPLCustomer(string iiplcustid, string abctime)
{
var accessToken = "CAACEdEose0cBADKYiSkFVcqeZAYxmYlytKM5pQT6zuEvnNoU9soPlWc2pZAJvKDL557BKTGIRNhbcuZBR6Li8TlrcM8yG1yXYGzikVlUPyFgDPzEDMiIZAnuHe5y3gTZCxkyTeA12ISPPRhJev6B63rTr05slMfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(iiplcustid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string[] splitname = name.Split(' ');
string link = obj["link"].ToString();
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myConnection1.Open();
SqlCommand myCommand1 = new SqlCommand(qy1, myConnection1);
myCommand1.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,link,firstname,lastname,cust_date,New) values('" + custid + "','" + name + "','" + link + "','" + splitname[0] + "','" + splitname[1] + "','" + abctime + "','1')";
SqlDataReader myReader1 = myCommand1.ExecuteReader();
myReader1.Close();
myConnection1.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = "SET DATEFORMAT MDY UPDATE fb_customer set name='" + name + "',firstname='" + splitname[0] + "',lastname='" + splitname[1] + "',link='" + link + "',cust_date='" + abctime + "' where customer_fb_id = '" + custid + "'";
//Here I'm getting an error
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
You can use Datetime.ParseExact method to convert date into appropriate format. Use like this
DateTime.ParseExact('07-12-2013', 'dd/MM/yyyy',
System.Globalization.CultureInfo.InvariantCulture).ToString('yyyy/MM/dd')
You need to change the format whatever you like.
This is gonna be very simple. Try the following format.
string date = DateTime.Now.ToString("MM/dd/yyyy HH:MM");
I just gave DateTime.Now and converted it. You can give the DateTime which you get and convert it to the format specified in the above syntax.