got this error in IF Condition - c#

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

Related

how to update weight in database

private void btn_Update_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update MyWeight set Weight='" + txt_Weight.Text + "'where Name='" + txt_Name.Text + "'";
string a = (string)cmd.ExecuteScalar();
con.Close();
if (a != null)
{
cmd.ExecuteNonQuery();
con.Close();
display_data();
MessageBox.Show("Weight updated successfuly!!!");
}
else
{
con.Close();
display_data();
MessageBox.Show("Not updated!!!");
}
}
I tried to update the weight into the database, but the database keeps saying that it is not updated.
Try like this:
bool updated;
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update MyWeight set Weight=#Weight where Name=#Name";
cmd.Parameters.Add(new SqlParameter("Weight", txt_Weight.Text));
cmd.Parameters.Add(new SqlParameter("Name", txt_Name.Text));
updated = (cmd.ExecuteNonQuery() > 1);
con.Close();
}
if (updated)
{
display_data();
MessageBox.Show("Weight updated successfuly!!!");
}
else
{
display_data();
MessageBox.Show("Not updated!!!");
}
It makes more sense to use ExecuteNonQuery for update operations in general because you don't expect any results.
Have you checked the table to see if it did update the row?
Why are you executing the same command with ExecuteNonQuery inside the if statement?

Asp.net Listview does not bind after performing insert operation

I have listview control in my page. I gets populated onPage load as well as when new record entered in the table. Problem is after performing InsertOperation I am calling It's bind method again but it doesn't refresh its data. Hence I debugged it & executed actual query in SQL & query returns with added rows.
protected void insertBulkPricing()
{
try {
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO bulk_pricing (productID, rangeFrom, rangeTo, price, time, discount, status) VALUES(#productID, #rangeFrom, #rangeTo, #price, #time, #discount, #status)";
cmd.Parameters.AddWithValue("#productID", productID.Text);
cmd.Parameters.AddWithValue("#rangeFrom", bulkRangeFrom.Text);
cmd.Parameters.AddWithValue("#rangeTo", bulkRangeTo.Text);
cmd.Parameters.AddWithValue("#price", bulkPrice.Text);
cmd.Parameters.AddWithValue("#time", bulkTime.Text);
cmd.Parameters.AddWithValue("#discount", bulkDiscount);
cmd.Parameters.AddWithValue("#status", "active");
cmd.Connection = con;
con.Open();
this.bindBulkPricing();
cmd.ExecuteNonQuery();
con.Close();
} catch (Exception ex) {
Response.Write(ex);
}
}
private void bindBulkPricing()
{
string action = Request.QueryString("action").ToString;
if (action == "new") {
productID.Text = rowNumber;
}
try {
string str = "select * from bulk_pricing where productID = #productID";
string conString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString;
MySqlConnection con = new MySqlConnection(conString);
MySqlCommand cmd = new MySqlCommand(str);
cmd.Parameters.AddWithValue("#productID", productID.Text);
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
bulkPriceList.DataSource = dt;
bulkPriceList.DataBind();
con.Close();
} catch (Exception ex) {
Response.Write(ex);
}
}
protected void insertBulkPricing()
{
try {
MySqlConnection con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings("conio2").ConnectionString();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO bulk_pricing (productID, rangeFrom, rangeTo, price, time, discount, status) VALUES(#productID, #rangeFrom, #rangeTo, #price, #time, #discount, #status)";
cmd.Parameters.AddWithValue("#productID", productID.Text);
cmd.Parameters.AddWithValue("#rangeFrom", bulkRangeFrom.Text);
cmd.Parameters.AddWithValue("#rangeTo", bulkRangeTo.Text);
cmd.Parameters.AddWithValue("#price", bulkPrice.Text);
cmd.Parameters.AddWithValue("#time", bulkTime.Text);
cmd.Parameters.AddWithValue("#discount", bulkDiscount);
cmd.Parameters.AddWithValue("#status", "active");
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.bindBulkPricing();
} catch (Exception ex) {
Response.Write(ex);
}
}
You only run cmd.ExecuteNonQuery() after run this.bindBulkPricing(). I hope it will work for you.

Must declare the scalar variable "#Emp_ID"

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/

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();
}
}

How do i check ID if it is already stored in database?

I have this code that Inserts data to database. I want to check if the ID going to be inserted is already in database. but if it is not in database it should be inserted. But has some errors, can you please help me out with it?
public void Add()
{
sc.Open();
try
{
cmd = new SqlCommand("Select idnum from TableVotersInfo Where idnum=#idnum", sc);
cmd.Parameters.AddWithValue("#idnum", _idnum);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read() == true)
{
MessageBox.Show("ID number already exist!");
rd.Close();
}
else
{
cmd = new SqlCommand("INSERT INTO TableVotersInfo (Education, idnum, FirstName, MiddleName, LastName, SchoolYear, ControlNum, VResult) VALUES (#ed, #idnum, #firstname, #middlename, #lastname, #schoolyear, #controlnum, 'Not Voted');", sc);
cmd.Parameters.AddWithValue("#id", _id);
cmd.Parameters.AddWithValue("#ed", _ed);
cmd.Parameters.AddWithValue("#idnum", _idnum);
cmd.Parameters.AddWithValue("#firstname", _firstname);
cmd.Parameters.AddWithValue("#middlename", _middlename);
cmd.Parameters.AddWithValue("#lastname", _lastname);
cmd.Parameters.AddWithValue("#schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("#controlnum", _controlnum);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Stored Successfully!");
FAddVoters._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
Edit
My error now is There is already an open DataReader associated with this command which must be closed first..
Update
public void Update()
{
sc.Open();
try
{
cmd = new SqlCommand("UPDATE TableVotersInfo SET Education=#ed, idnum=#idnum, FirstName=#firstname, MiddleName=#middlename, LastName=#lastname, SchoolYear=#schoolyear, ControlNum=#controlnum WHERE id=#id", sc);
cmd.Parameters.AddWithValue("#id", _id);
cmd.Parameters.AddWithValue("#ed", _ed);
cmd.Parameters.AddWithValue("#idnum", _idnum);
cmd.Parameters.AddWithValue("#firstname", _firstname);
cmd.Parameters.AddWithValue("#middlename", _middlename);
cmd.Parameters.AddWithValue("#lastname", _lastname);
cmd.Parameters.AddWithValue("#schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("#controlnum", _controlnum);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("Successfully Updated!");
FAddVoters._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
try remove single quotes in query like this
cmd = new SqlCommand("Select idnum from TableVotersInfo Where idnum=#idnum", sc);
and change type of variable _idnum from string to int
for solve error in insert try this code
public void Add()
{
sc.Open();
try
{
cmd = new SqlCommand("Select idnum from TableVotersInfo Where idnum=#idnum", sc);
cmd.Parameters.AddWithValue("#idnum", _idnum);
if (cmd.ExecuteScalar() != null)
{
MessageBox.Show("ID number already exist!");
}
else
{
cmd = new SqlCommand("INSERT INTO TableVotersInfo (Education, idnum, FirstName, MiddleName, LastName, SchoolYear, ControlNum, VResult) VALUES (#ed, #idnum, #firstname, #middlename, #lastname, #schoolyear, #controlnum, 'Not Voted');", sc);
cmd.Parameters.AddWithValue("#id", _id);
cmd.Parameters.AddWithValue("#ed", _ed);
cmd.Parameters.AddWithValue("#idnum", _idnum);
cmd.Parameters.AddWithValue("#firstname", _firstname);
cmd.Parameters.AddWithValue("#middlename", _middlename);
cmd.Parameters.AddWithValue("#lastname", _lastname);
cmd.Parameters.AddWithValue("#schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("#controlnum", _controlnum);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Stored Successfully!");
FAddVoters._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
Instead of two queries you could do it in one by changing values to a select and adding a where clause. After doing that you just need to check the returned value of ExecuteNonQuery() to see if 0 or 1 row was updated.
public void Add()
{
sc.Open();
try
{
using(cmd = new SqlCommand(#"INSERT INTO TableVotersInfo (Education, idnum, FirstName, MiddleName, LastName, SchoolYear, ControlNum, VResult)
SELECT #ed, #idnum, #firstname, #middlename, #lastname, #schoolyear, #controlnum, 'Not Voted'
WHERE #idNum NOT IN (SELECT idNum FROM TableVotersInfo);", sc))
{
cmd.Parameters.AddWithValue("#id", _id);
cmd.Parameters.AddWithValue("#ed", _ed);
cmd.Parameters.AddWithValue("#idnum", _idnum);
cmd.Parameters.AddWithValue("#firstname", _firstname);
cmd.Parameters.AddWithValue("#middlename", _middlename);
cmd.Parameters.AddWithValue("#lastname", _lastname);
cmd.Parameters.AddWithValue("#schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("#controlnum", _controlnum);
var rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected == 0)
{
MessageBox.Show("ID number already exist!");
}
else
{
MessageBox.Show("Data Stored Successfully!");
FAddVoters._cleardata = cleardata;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
try cmd.Dispose(); in else {} before again initializing the command object.
This should work in your case.
Close the datareader object in else also

Categories