Confirm order button does not works as expected - asp.net

I am creating an Shopping website as my project in asp.net but the problem am facing is that when a user clicks on confirm order button then data is not getting inserted in the database. To be more clear, This is working when i use the User created directly in the table but when i use the User created using registration form then its not working(i can login with this user id as data is inserted in the table). Also its not even providing any error message and is just redirecting to invoice page as i coded but without inserting data into the table.....Strange error i can ever imagine any help will be appreciated. Waiting for your reply. Thank You
this one i think maybe creating problem
ArrayList ar = new ArrayList();
ArrayList ar1 = new ArrayList();
ArrayList ar2 = new ArrayList();
ArrayList ar3 = new ArrayList();
SqlCommand command = new SqlCommand("Select Product_id,Product_name,Product_cost,Quantity from Cart where User_id='" + userid + "'",con);
try
{
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int a = Convert.ToInt32(reader[0]);
ar.Add(a);
String pdname = reader[1].ToString();
ar1.Add(pdname);
int pcost = Convert.ToInt32(reader[2]);
ar2.Add(pcost);
int q = Convert.ToInt32(reader[3]);
ar3.Add(q);
}
pkid = (int[]) ar.ToArray(typeof(int));
pkname = (String[]) ar1.ToArray(typeof(String));
pkcost = (int[]) ar2.ToArray(typeof(int));
pkq = (int[]) ar3.ToArray(typeof(int));
con.Close();
}
catch (Exception ex)
{
Response.Write("Error at second" + ex);
}
try
{
con.Open();
for (int i = total-1; i>=0; i--)
{
SqlCommand smd = new SqlCommand("Insert into Orders values('"+orderid+"','" + userid + "','" + name + "','" + pkid[i] + "','" + pkname[i] + "','" + address + "','" + pkq[i] + "','" + pkcost[i] + "','" + date + "','" + payment.SelectedItem.ToString() + "','Pending')", con);
smd.ExecuteNonQuery();
}
con.Close();
}

Ok so my probelm is solve. The solution for this was that i just remove try catch block and thats it its working as expected. Anyways i don't know yet what its not working using try catch block.

Related

Inserting All of CheckBoxList Data into DB

I have a form that users will fill out and when they submit, all data is pushed to a database.
My Problem is that I have a CheckBoxList and if a user selects multiple checkboxes it only inputs the first item into the database. How do I make it so that all the items are inputted into the same row and separated by commas.
Here is my current code:
protected void Button1_Click(object sender, EventArgs e)
{
//Start Code
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = conString + txtFirst.Text + "','" + txtLast.Text +
"','" + txtEmail.Text + "','" + lstBranch.Text + "','" + lstAccess.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
}
You can loop the items like this
string result = string.Empty;
for (int i = 0; i < checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
result += checkboxlist1.Items[i].Text + ", ";
}
}
// remove the final comma.
// add 'result' to your sql stmt.

How to managed two sql queries in ASP.Net (Visual Studio 2010)

So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();

Data is not inserted into database using windows application but not showing any error

Button Click Code
String cs = null;
SqlConnection scon = null;
SqlCommand cmd = null;
private void btnOk_Click(object sender,EventArgs e)
{
String name = txtBoxName.Text.ToString();
String mobile = txtBoxMobile.Text.ToString();
String address = txtBoxAddress.Text.ToString();
String ty = null;
if (radioButtonCow.Checked)
{
ty = radioButtonCow.Text.ToString();
}
else {
ty = radioButtonBuffalo.Text.ToString();
}
int n = 0;
using(scon = new SqlConnection(cs)){
scon.Open();
String query = "insert into new_customer(name,mobile,address,type)
values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";
cmd = new SqlCommand(query, scon);
n = cmd.ExecuteNonQuery();
}
}
private void NewCustomer_Load(object sender, EventArgs e)
{
cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
}
}
When I run this application it runs successfully without showing any error but it doesn't insert any records in the table. The table has the fields id, name, mobile, address and type. id is a primary key and it's an identity field. All the other fields are of varchar type.
Why doesn't it insert data in the table?
You just pass your parameters in this way as i mentioned below,
SqlConnection scon = new SqlConnection(cs);
scon.Open();
String query = "insert into new_customer values(#name,#mobile,#address,#type)";
cmd = new SqlCommand(query, scon);
cmd.Parameters.AddWithValue("#name",name);
cmd.Parameters.AddWithValue("#name",mobile);
cmd.Parameters.AddWithValue("#name",address);
cmd.Parameters.AddWithValue("#name",ty);
cmd.ExecuteNonQuery();
scon.Close();
try by wrap the type field as [type]
String query = "insert into new_customer(name,mobile,address,[type]) values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";

Insert data into database in ASP.NET throwing exception

I'm trying to insert data into database in ASP.NET with this code:
string conn = "TJLDatabaseConnectionString";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption) Values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')", objsqlconn);
objcmd.ExecuteNonQuery();
//MessageBox.Show("Successful");
But when I run it. It gives the following message:
First the important, always use sql-parameters to prevent sql-injection. Never concatenate parameters into a sql-query. This can also solve localization or "escaping" issues.
Also, use the using statement to ensure that anything using unmanaged resources (like a sql-connection) will be closed and disposed even on error:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption)";
using(var objsqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
using (var cmd = new SqlCommand(sql, objsqlconn))
{
cmd.Parameters.AddWithValue("#MachineName", TextBox1.Text);
cmd.Parameters.AddWithValue("#LastReading", TextBox2.Text);
cmd.Parameters.AddWithValue("#CurrentReading", TextBox3.Text);
cmd.Parameters.AddWithValue("#Consumption", TextBox4.Text);
objsqlconn.Open();
int insertedCount = cmd.ExecuteNonQuery();
}
Side-note: if you have an identity column and you want to retrieve the newly created primary-key, use SCOPE_IDENTITY and ExecuteScalar even if you use INSERT INTO:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption);
SELECT CAST(scope_identity() AS int)";
//...
int newID = (int)cmd.ExecuteScalar();
Use a variable to check if row is getting affected or not
rowAffected= objcmd.ExecuteNonQuery();
if(rowAffected >0)
{
//sucessful
}
else
{
//
}
Since there is no any exception mention in your question so just for a better and readable code I would suggest you too use using blocks. It gives you nice, cleaner and readable code and also handle objects when they go out of scope.
This is meant for good practices that we generlly follow while coding. Kindly show us the exception for appropriate solution.
private void ConnectToDb()
{
var conn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using( var conn = new SqlConnection(conn))
{
conn.Open();
var cmdtxt ="Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption)
Values(#P1,#P2,#P3,#P4)";
using(var cmd = new SqlCommand(cmdtxt, conn))
{
cmd.CommandType=CommandType.Text;
cmd.Parameters.AddWithValue("#P1", TextBox1.Text);
cmd.Parameters.AddWithValue("#P2", TextBox2.Text);
cmd.Parameters.AddWithValue("#P3", TextBox3.Text);
cmd.Parameters.AddWithValue("#P4", TextBox4.Text);
cmd.ExecuteNonQuery();
}
con.close();
}
}

what is wrong with this C# duplicate row code?

I'm trying to duplicate a record in my database and I used this code you see below, the sql query worked perfectly in sql server but here I don't know what the problem...help me please
//Insert new Order
int newOrderId = 0;
if (e.CommandName == "Repeat")
{
try
{
SqlConnection con = DataAccess.Connection.GetDBConnection();
//duplicate the jobs from the old order to the new added order
sqlCmd.Parameters.Clear();
string com2 = "Insert Into [OrderItems] (orderId, productId, quantity, [length], note, multipleSlip, internalDiameter, " +
"wall, machineReCuttingId,winderId, jobNote) (select #newOrderId, productId, quantity, [length], note, multipleSlip, " +
"internalDiameter, wall, machineReCuttingId, winderId, jobNote FROM OrderItems Where orderId=#oldOrderId)";
SqlCommand sqlCmd = new SqlCommand(com2, con);
sqlCmd.Parameters.Add("#newOrderId", SqlDbType.Int).Value = newOrderId;
//assign the old order Id to the insert parameter #oldOrderId
sqlCmd.Parameters.Add("#oldOrderId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument);
sqlCmd.ExecuteNonQuery();
StatusLabel.Text = "The New Order is" + newOrderId.ToString() + " The Old order ID is: " + e.CommandArgument.ToString();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
OrderGridView.DataSource = ViewDataSource(selectCustomer);
OrderGridView.DataBind();
// Response.Redirect("../Orders/AddNewOrder.aspx?customerId=" + selectCustomer + "&" + "orderId=" + newOrderId);
}
By the way I tested the values of newOrderId and the oldOrderId they are both correct

Resources