Adding values of one table into another with INSERT INTO ... SELECT - c#

I need to add value to table sales(acnum,scriptname,shares_bought) from transac(acnum,scriptname,Quantity,Price) using c# in visual studio 2008. I am using the code shown below, but it is not inserting value into sales database.
It is not showing any error or exception but its not updating sales table also.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
Con.Open();
string insertsale = "INSERT INTO sales(acnum, scriptname, shares_bought) select acnum,scriptname,Quantity from transac";
SqlCommand cmd = new SqlCommand(insertsale, Con);
cmd.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}

The problem was that I had used PostUrl for the button click . . so i think it was redirecting to the nextpage without processing the code. Now its fixed .

Related

Update statement does nothing

When I enter a number in the ChbBeds_numericUpDown and click on the "Update" button, it says "Data Updated", but nothing changes in the database
private void ChbUp_button_Click(object sender, EventArgs e)
{
try
{
string statement = "UPDATE ChamberXPavilions SET Beds count = #beds_count WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number";
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Data updated");
showdata();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Is the SQL statement wrong ?
Contrary to SQL Server, the OleDB provider for MS Access does NOT work with named parameters - instead, it uses positional parameters.
In your case, you have a SQL statement
UPDATE ChamberXPavilions
SET Beds count = #beds_count
WHERE Pav_name = #pav_name AND Chamber_number = #chamber_number
so you need to also provide the parameters in the same order - first #beds_count, then #pav_name and finally #chamber_number.
So try this for providing the parameter values:
cmd = new OleDbCommand(statement, conn);
cmd.Parameters.AddWithValue("#beds_count", ChbBeds_numericUpDown.Value);
cmd.Parameters.AddWithValue("#pav_name", Chbpav_comboBox.Text);
cmd.Parameters.AddWithValue("#chamber_number", Chb_numericUpDown.Value);
Now, your UPDATE statement should get the proper values and should now work

Writing to a SQLite Database in C#

Using Visual Studio/ Windows Forms, I am trying to write data to a SQLite DB.
The Event handler for the "submit" button is supposed to take the information in the relevant textboxes and write them to the corresponding fields in the DB.
The database connection and location is handled in the dbConnect class, and works as the login form works.
When the submit button is clicked however, nothing happens, no error message, nothing.
Can you see anything glaring?
private void button2_Click(object sender, EventArgs e)
{
try
{
//write new customer data to db
using (SQLiteConnection dbcon = new SQLiteConnection(conString))
{
dbcon.ConnectionString = dbConnect.source;
string sql;
{
sql = "INSERT INTO guest(forename,surname,telnumber,email,address)"
+ " Values(#f,#l,#tel,#em,#ad)";
}
using (SQLiteCommand cmd = new SQLiteCommand(sql, dbcon))
{
cmd.Parameters.AddWithValue("f", foreTB.Text);
cmd.Parameters.AddWithValue("l", surTB.Text);
cmd.Parameters.AddWithValue("tel", telTB.Text);
cmd.Parameters.AddWithValue("em", emailTB.Text);
cmd.Parameters.AddWithValue("ad", addTB.Text);
//perform db operation
dbcon.Open();
cmd.ExecuteNonQuery();
dbcon.Close();
}
}
//display relevant action feedback message
{
showlabel("New Customer Added OK", 4000);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}

c# mysql - add the value of stock and new entries when the description is the same

Sorry guys to my english..
when i insert a record the same description with the existing record in datagridview but different quantity.. it creates a new row for the last record i inserted...
what i want is to ADD the quantity i inserted to the old record with the same description..
1. HERE'S THE IMAGE FOR YOU TO UNDERSTAND THE PROBLEM
2. THIS IS WHAT HAPPEN
The result should be QUANTITY = 25.. and also the totalcbm.. totalcbm = quantity * cbm
private void btnSave_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO Inventory(Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm)VALUES(#Quantity,#Unit,#ItemCode,#ItemName,#Cbm,#TotalCbm)";
cmd.Parameters.AddWithValue("#Quantity", tbQuantity.Text.ToString());
cmd.Parameters.AddWithValue("#Unit", tbUnit.Text.ToString());
cmd.Parameters.AddWithValue("#ItemCode", tbItemCode.Text.ToString());
cmd.Parameters.AddWithValue("#ItemName", tbItemName.Text.ToString());
cmd.Parameters.AddWithValue("#Cbm", tbCbm.Text.ToString());
cmd.Parameters.AddWithValue("#TotalCbm", tbTotalCbm.Text.ToString());
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
frmUserAE form1 = new frmUserAE();
AccountForm.LoadGrid();
this.Hide();
}
}
}
You are doing an INSERT statement, which will create a new row.
You should do an UPDATE statement, depending on what you think is your primary key (the description?).

Update is not working nor throwing an error

I trying to update a record from ASP.Net page but there is no problem with the script and I am not receiving any error. Any suggestion are appreciated.
protected void update()
{
try
{
using (SqlConnection con = new SqlConnection(str))
{
string command = #"update dbo.Programs set ProgCode=#ProgCode,ProgTitle=#ProgTitle,ProgDescription=#ProgDescription,ProgBudget=#ProgBudget,ProgStartDate=#ProgStartDate,ProgEndDate=#ProgEndDate where ProgId=#ProgId";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#ProgId", Request.QueryString["UpdProg"]);
cmd.Parameters.AddWithValue("#ProgCode", Code.Text);
cmd.Parameters.AddWithValue("#ProgTitle", Titlebox.Text);
cmd.Parameters.AddWithValue("#ProgDescription", Description.Text);
cmd.Parameters.AddWithValue("#ProgBudget", Budget.Text);
cmd.Parameters.AddWithValue("#ProgStartDate", StartDate.Text);
cmd.Parameters.AddWithValue("#ProgEndDate", EndDate.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Status.Text = ex.ToString();
}
}
When the Update button is clicked this method is executed:
protected void UpdateRecord(object sender, EventArgs e)
{
update();
}
Thank you for your comments the problems is solved i was calling another method (UpdateSelector) on Page_Load that was making the problem

Registration page error in .NET

i'm a newbie in .NET and C# field.
I'm creating a Registration page to a website im working on.
i keep getting an error when registering to a website i'm creating. When entering my details, it doesn't register me to the database.
I created the a table in the database(i created a connectionString), and yet i cannot register - i get an exception that says "error,please try registering again" (as i did).
Does someone know what am i doing wrong?! Thanks!
here's my code and images:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from Table where Username='" + TextBox1Username.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
// int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
/* if (temp == 1)
{
Response.Write("username already exists");
} */
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionStr ing);
con.Open();
string insCmd = "Insert into Table (Username, Password, EmailAddress,Fullname, City) values (#Username, #Password, #EmailAddress, #Fullname, #City)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error,please try registering again");
}
}
}
image:
[URL=http://imageshack.us/photo/my-images/4/os6b.jpg/][IMG=http://img4.imageshack.us/img4/2526/os6b.jpg][/IMG][/URL]
Uploaded with [URL=http://imageshack.us]ImageShack.us[/URL]
you are missing fullname in your parameter and you have password twice.fix that and run it again.
Also, in your catch block.. you should use exception message to debug or log somewhere where you can see the error clearly. the way you have it right now gives the error you typed. not actual message.
here is link where they are discussing about sqlexception. might be good idea to catch that.
SqlException catch and handling
You pass two times the password parameter in the insert query. The second one is in place of the #fullname parameter.
This will cause your insert command to fail because you don't provide the #fullname parameter expected by the query.
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBox???????.Text); //<- Get from the correct textbox
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
You could have found this problem yourself if, inside the catch, you had added the er.Message to your Response
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error: " + er.Message + " ,please try registering again");
}

Categories

Resources