Must declare the scalar variable "#Emp_ID" - c#

con.Open();
//stringquery=("insert into Tbl_EmployeeDetails values='"+txtName.Text+"','"+txtContact.Text+"','"+txtAddress.Text+"','"+txtEmployeeID.Text+"','"+txtJobLocation.Text+"','"+txtDateOfBirth.Text+"','"+Rdllist.selectedItem.Text+"'");
//sql command cmd=new sqlcommand(query,con);
//cmd.ExecuteNonquery();
SqlCommand cmd= new SqlCommand("Insert into Tbl_EmployeeDetails(Name,Address,Contact,Emp_ID,JobLocation,DateOfBirth,Gender)values(#Name,#Address,#Contact,#Emp_ID,#JobLocation,#DateOfBirth,#Gender)",con);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Contact", txtContact.Text);
cmd.Parameters.AddWithValue("#Employee_ID", txtEmp_ID.Text);
cmd.Parameters.AddWithValue("#JobLocation", txtJobLocation.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", txtDateOfBirth.Text);
cmd.Parameters.AddWithValue("#Gender", Rdllist.SelectedItem.Text);
cmd.ExecuteNonQuery();
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),"alertMessage","alert('Record Inserted Successfully')",true);
txtName.Text= String.Empty;
txtAddress.Text= String.Empty;
txtContact.Text= String.Empty;
txtEmp_ID.Text= String.Empty;
txtJobLocation.Text= String.Empty;
txtDateOfBirth.Text= String.Empty;
// txtGender.Text= String.Empty;
con.Close();
}
}

#Employee_ID should be #Emp_ID the same as it is with your query.
eg:
cmd.Parameters.AddWithValue("#Emp_ID", txtEmp_ID.Text);
Hence try this:
con.Open();
SqlCommand cmd= new SqlCommand("Insert into Tbl_EmployeeDetails(Name,Address,Contact,Emp_ID,JobLocation,DateOfBirth,Gender)values(#Name,#Address,#Contact,#Emp_ID,#JobLocation,#DateOfBirth,#Gender)",con);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Contact", txtContact.Text);
cmd.Parameters.AddWithValue("#Emp_ID", txtEmp_ID.Text);
cmd.Parameters.AddWithValue("#JobLocation", txtJobLocation.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", txtDateOfBirth.Text);
cmd.Parameters.AddWithValue("#Gender", Rdllist.SelectedItem.Text);
cmd.ExecuteNonQuery();
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),"alertMessage","alert('Record Inserted Successfully')",true);
txtName.Text= String.Empty;
txtAddress.Text= String.Empty;
txtContact.Text= String.Empty;
txtEmp_ID.Text= String.Empty;
txtJobLocation.Text= String.Empty;
txtDateOfBirth.Text= String.Empty;
// txtGender.Text= String.Empty;
con.Close();
}
}

Or you can just change your values to:
values(#Name,#Address,#Contact,#Employee_ID,#JobLocation,#DateOfBirth,#Gender)
Since you called it like this:
cmd.Parameters.AddWithValue("#Employee_ID", txtEmp_ID.Text);
or
values(#Name,#Address,#Contact,#Emp_ID,#JobLocation,#DateOfBirth,#Gender)
cmd.Parameters.AddWithValue("#Emp_ID", txtEmp_ID.Text);
Whatever the name in values is going to be used in cmd.parameters.addwithvalue.
Beware of the pitfalls of AddWithValue: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Related

inserting from textbox and datagridview at sametime in database

how can I insert data from datagridview and textboxes at same time with one button click in one table. here is my code I use foreachloop to insert from DataGridview but it insert null
any help appreciate.
SqlCommand cmd, cmd1, cmd2, cmd3;
con.Open();
cmd = new SqlCommand("insert into sale_detail(sale_bill_number, discount,currency,date) values(#sale_bill_number, #discount ,#currency,#date)", con);
cmd.Parameters.AddWithValue("#sale_bill_number", billbox.SelectedItem);
cmd.Parameters.AddWithValue("#discount", txtdiscount.Text);
cmd.Parameters.AddWithValue("#currency", currencyid);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value.Date);
cmd1 = new SqlCommand("insert into payment(sdetail,totalprice) values(#sdetail,#totalprice)", con);
cmd1.Parameters.AddWithValue("#sdetail", sid);
cmd1.Parameters.AddWithValue("#totalprice", txtpayment.Text);
cmd2 = new SqlCommand("insert into sale(customer) values(#customer)", con);
cmd2.Parameters.AddWithValue("#customer", customerid);
foreach (DataGridViewRow dr in saleDataGridView.Rows)
{
string sqlquery = "insert into sale_detail(medicine_id,purchase_rate,quantity)values(#medicine_id,#purchase_rate, #quantity)";
cmd = new SqlCommand(sqlquery, con);
cmd.Parameters.AddWithValue("#medicine_id", dr.Cells["شماره مسلسل"].Value);
// cmd.Parameters.AddWithValue("#country", saleDataGridView.Rows[i].Cells["کشور"].Value);
cmd.Parameters.AddWithValue("#purchase_rate", dr.Cells["قیمت"].Value);
// cmd.Parameters.AddWithValue("#sale_rate", dr.Cells["قیمت فروش"].Value ??DBNull.Value);
cmd.Parameters.AddWithValue("#quantity", dr.Cells["تعداد"].Value);
}
if (cmd.ExecuteNonQuery() == 1)
{
if (cmd1.ExecuteNonQuery() == 1) {
if (cmd2.ExecuteNonQuery() == 1)
{
Perhaps:
using con = new SqlCommand(...);
con.Open();
var tran = con.BeginTransaction();
var cmd = new SqlCommand("insert into sale_detail(sale_bill_number, discount,currency,date) values(#sale_bill_number, #discount ,#currency,#date)", con);
cmd.Parameters.AddWithValue("#sale_bill_number", billbox.SelectedItem);
cmd.Parameters.AddWithValue("#discount", txtdiscount.Text);
cmd.Parameters.AddWithValue("#currency", currencyid);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value.Date);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into payment(sdetail,totalprice) values(#sdetail,#totalprice)", con);
cmd.Parameters.AddWithValue("#sdetail", sid);
cmd.Parameters.AddWithValue("#totalprice", txtpayment.Text);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("insert into sale(customer) values(#customer)", con);
cmd.Parameters.AddWithValue("#customer", customerid);
cmd.ExecuteNonQuery();
foreach (DataGridViewRow dr in saleDataGridView.Rows)
{
string sqlquery = "insert into sale_detail(medicine_id,purchase_rate,quantity)values(#medicine_id,#purchase_rate, #quantity)";
cmd = new SqlCommand(sqlquery, con);
cmd.Parameters.AddWithValue("#medicine_id", dr.Cells["شماره مسلسل"].Value);
// cmd.Parameters.AddWithValue("#country", saleDataGridView.Rows[i].Cells["کشور"].Value);
cmd.Parameters.AddWithValue("#purchase_rate", dr.Cells["قیمت"].Value);
// cmd.Parameters.AddWithValue("#sale_rate", dr.Cells["قیمت فروش"].Value ??DBNull.Value);
cmd.Parameters.AddWithValue("#quantity", dr.Cells["تعداد"].Value);
cmd.ExecuteNonQuery();
}
tran.Commit();
And wrap the whole thing(apart from the using) in a try catch (I would have done it but I'm on a cellphone; there is no code indent button) and put tran.Rollback(); in the catch

Update and insert in one button with Command Parametrs C#

I want to do update and insert in one button.
i want it to check if there's data then it will just update it but if not it will add it.
I don't know what i'm missing in this code
cnx.Open();
SqlCommand cmd = cnx.CreateCommand();
SqlDataReader dr;
cmd.CommandText = "Select * from TPayement where ID='" + txt_ID.Text + "'";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
cmd.CommandText = "update TPayement (ID, Nom, QUA, Salaire, NombreJour, HeurSupplimentaire, SalaireHeur, Somme) values (#ID, #Nom, #QUA, #Salaire, #NombreJour, #HeurSupplimentaire, #SalaireHeur, #Somme) where ID='" + txt_ID.Text + "'";
cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.Parameters.Add("#Nom", SqlDbType.VarChar, 50);
cmd.Parameters.Add("#QUA", SqlDbType.VarChar, 50);
cmd.Parameters.Add("#Salaire", SqlDbType.Float);
cmd.Parameters.Add("#NombreJour", SqlDbType.Float);
cmd.Parameters.Add("#HeurSupplimentaire", SqlDbType.Float);
cmd.Parameters.Add("#SalaireHeur", SqlDbType.Float);
cmd.Parameters.Add("#Somme", SqlDbType.Float);
cmd.Parameters["#ID"].Value = txt_ID.Text;
cmd.Parameters["#Nom"].Value = txt_Nom.Text;
cmd.Parameters["#QUA"].Value = txt_QUA.Text;
cmd.Parameters["#Salaire"].Value = txt_Salaire.Text;
cmd.Parameters["#NombreJour"].Value = txt_NBRJ.Text;
cmd.Parameters["#HeurSupplimentaire"].Value = txt_HSUP.Text;
cmd.Parameters["#SalaireHeur"].Value = txt_SalireHeur.Text;
cmd.Parameters["#Somme"].Value = txt_Somme.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Se payement est enregistrer");
}
else
{
cmd.CommandText = "insert into TPayement (ID, Nom, QUA, Salaire, NombreJour, HeurSupplimentaire, SalaireHeur, Somme) values (#ID, #Nom, #QUA, #Salaire, #NombreJour, #HeurSupplimentaire, #SalaireHeur, #Somme)";
cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.Parameters.Add("#Nom", SqlDbType.VarChar, 50);
cmd.Parameters.Add("#QUA", SqlDbType.VarChar, 50);
cmd.Parameters.Add("#Salaire", SqlDbType.Float);
cmd.Parameters.Add("#NombreJour", SqlDbType.Float);
cmd.Parameters.Add("#HeurSupplimentaire", SqlDbType.Float);
cmd.Parameters.Add("#SalaireHeur", SqlDbType.Float);
cmd.Parameters.Add("#Somme", SqlDbType.Float);
cmd.Parameters["#ID"].Value = txt_ID.Text;
cmd.Parameters["#Nom"].Value = txt_Nom.Text;
cmd.Parameters["#QUA"].Value = txt_QUA.Text;
cmd.Parameters["#Salaire"].Value = txt_Salaire.Text;
cmd.Parameters["#NombreJour"].Value = txt_NBRJ.Text;
cmd.Parameters["#HeurSupplimentaire"].Value = txt_HSUP.Text;
cmd.Parameters["#SalaireHeur"].Value = txt_SalireHeur.Text;
cmd.Parameters["#Somme"].Value = txt_Somme.Text;
dr.Close();
cmd.ExecuteNonQuery();
MessageBox.Show("Se payement est enregistrer");
}
dr.Close();
cnx.Close();
The problem is that you open a DataReader with the Command object cmd.
Then, before you close the DataReader, you try to re-purpose the same cmd object and Execute it.
You have to close the DataReader before you can re-use the cmd object for an insert or update.

Insert more than one item from checkedlistbox to AccessDB

I have a listcheckedbox that lists the employee numbers and I want to be able to add each employee that attended a training class to show up under a training session. However, when I try to submit the information to insert into the DB, it will only add one of the employees selected. How can I have it submit more than 1 employee to a class session?
try
{
string cmdstring = "INSERT INTO [SESSION] (PrincipleName, Comments, SessionDate, SessionName, TellerNum) VALUES (#principle, #comments, #date, #session, #teller)";
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#principle", comboBox12.Text);
cmd.Parameters.AddWithValue("#comments", textBox3.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#session", comboBox1.Text);
cmd.Parameters.AddWithValue("#teller", checkedListBox1.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Submitted Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
Here is my updated code after the answer from LarsTech answer
con.Open();
string cmdstring = "INSERT INTO [SESSION] (PrincipleName, Comments, SessionDate, SessionName, TellerNum) VALUES (#principle, #comments, #date, #session, #teller)";
foreach (int s in checkedListBox1.CheckedItems)
{
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#principle", comboBox12.Text);
cmd.Parameters.AddWithValue("#comments", textBox3.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value.ToShortDateString());
cmd.Parameters.AddWithValue("#session", comboBox1.Text);
cmd.Parameters.AddWithValue("#teller", s);
cmd.ExecuteNonQuery();
}
}
con.Close();
MessageBox.Show("Submitted Successfully");
textBox3.Clear();
checkedListBox1.ClearSelected();
comboBox1.Refresh();
comboBox12.Refresh();
dateTimePicker1.Refresh();
You have to iterate over the CheckedItems collection:
foreach (string s in checkedListBox1.CheckedItems)
{
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#principle", comboBox12.Text);
cmd.Parameters.AddWithValue("#comments", textBox3.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#session", comboBox1.Text);
cmd.Parameters.AddWithValue("#teller", s);
cmd.ExecuteNonQuery();
}
}

UPDATE query on Access Database not working C#.NET

I am working on a database management system. I have a simple task of updating user profile. I created an asp.net page with textboxes and a save button. After adding the text I click on the save button. The code for the button is
protected void Button1_Click(object sender, EventArgs e)
{
string firstName = TextBox2.Text;
string lastName = TextBox1.Text;
string sCourse = TextBox3.Text;
string sTelephone = TextBox4.Text;
string sAddress = TextBox5.Text;
string sEmail = TextBox6.Text;
string Gender = TextBox7.Text;
string user = User.Identity.Name;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\ASPNetDB.accdb");
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Email", sEmail);
oleDBConn.Open();
cmd.ExecuteNonQuery();
}
But nothing happens. The database is not updated. Is the code correct?
Add the parameter values in the same order as the parameter names appear in the UPDATE statement.
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
OleDb with Access does not pay attention to the parameter names, only their order.
add the parameters according to the order in the query
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);

got this error in IF Condition

Here i'm going to register a user.Finally i wanted to check If registeration successful then needs to go next page..I got thie error in IF Condition
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=AAZZZ;Initial Catalog=DRDB;User ID=sa;Password=sa123");
SqlCommand cmd = new SqlCommand("UserRegistration_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Firstname", TextBox1.Text);
cmd.Parameters.AddWithValue("#Lastname", TextBox2.Text);
cmd.Parameters.AddWithValue("#Username", TextBox3.Text);
cmd.Parameters.AddWithValue("#Password", TextBox4.Text);
cmd.Parameters.AddWithValue("#ConfirmPassword", TextBox5.Text);
cmd.Parameters.AddWithValue("#Address1", TextBox6.Text);
cmd.Parameters.AddWithValue("#Address2", TextBox7.Text);
cmd.Parameters.AddWithValue("#Address3", TextBox8.Text);
cmd.Parameters.AddWithValue("#Telephone", TextBox9.Text);
cmd.Parameters.AddWithValue("#Email", TextBox10.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
if (Registration == Successful)
{
Response.Redirect("Registration2.aspx");
}
else {
lblinfo.Text = "Some error has happend";
}
}
I assuming that you are doing and Insert or Update and not sure what are the values for Registration == Succesful or how are you getting them
So check if cmd.ExecuteNonQuery() does not return -1 because -1 means a rollback
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result != -1)
{
Response.Redirect("Registration2.aspx");
}
else {
lblinfo.Text = "Some error has happend";
}
Are you just trying to determine if the SQL query processed/affected any rows?
SqlConnection con = new SqlConnection("Data Source=AAZZZ;Initial Catalog=DRDB;User ID=sa;Password=sa123");
SqlCommand cmd = new SqlCommand("UserRegistration_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Firstname", TextBox1.Text);
cmd.Parameters.AddWithValue("#Lastname", TextBox2.Text);
cmd.Parameters.AddWithValue("#Username", TextBox3.Text);
cmd.Parameters.AddWithValue("#Password", TextBox4.Text);
cmd.Parameters.AddWithValue("#ConfirmPassword", TextBox5.Text);
cmd.Parameters.AddWithValue("#Address1", TextBox6.Text);
cmd.Parameters.AddWithValue("#Address2", TextBox7.Text);
cmd.Parameters.AddWithValue("#Address3", TextBox8.Text);
cmd.Parameters.AddWithValue("#Telephone", TextBox9.Text);
cmd.Parameters.AddWithValue("#Email", TextBox10.Text);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0) // I assume you want rows to be affected
{
Response.Redirect("Registration2.aspx");
}
else
{
lblinfo.Text = "Some error has happend";
}
MSDN - "For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1."

Categories