What is wrong with my code? Pls Help. I keep getting error System.Threading.ThreadAbortException: Thread was being aborted.
This is my registration page c# code as below:
protected void submitbtn_Click(object sender, EventArgs e)
{
try
{
con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS;Integrated Security=True";
con.Open();
string insertQuery = "insert into account" + "(username,password) values (#username,#password)";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#username", TextBoxUN.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPass.Text);
cmd.ExecuteNonQuery();
string insertQuery1 = "insert into parent" + "(Email,Contact,FName,LName,HomeAddress,Gender) values (#Email,#Contact,#FName,#LName,#HomeAddress,#Gender)";
SqlCommand cmd1 = new SqlCommand(insertQuery1, con);
cmd1.Parameters.AddWithValue("#Email", TextBoxEmail.Text);
cmd1.Parameters.AddWithValue("#Contact", TextBoxContact.Text);
cmd1.Parameters.AddWithValue("#FName", TextBoxFName.Text);
cmd1.Parameters.AddWithValue("#LName", TextBoxLName.Text);
cmd1.Parameters.AddWithValue("#HomeAddress", TextBoxHome.Text);
cmd1.Parameters.AddWithValue("#Gender", DropDownListGender.SelectedItem.ToString());
cmd1.ExecuteNonQuery();
MessageBox.Show("Registration is successfull!");
Response.Redirect("Login.aspx");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
}
}
}
There is already an answer here: Why Response.Redirect causes System.Threading.ThreadAbortException?
This is caused by your Response.Redirect.
Also, it might be better to use:
using(SqlCommand cmd = new SqlCommand(insertQuery, conn)
{
// The sql command code here like parameters, etc.
}
Using dispose immediatly the SqlCommand. It might prevent error since you are using multiple SqlCommand.
Related
I'm building an application using C# and have decided to go with a windows Form. The goal is to have a user register and be able to login with their login credentials they set up in the registration form.
Registration Form:
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
connetionString = #"Data Source=THANATOS\SQLEXPRESS01;Initial Catalog=LoginDatabase;Integrated Security=True";
SqlConnection cnn = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.Parameters.AddWithValue("#FirstName", first_NameTextBox.Text);
cmd.Parameters.AddWithValue("#LastName", last_NameTextBox.Text);
cmd.Parameters.AddWithValue("#Username", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#Password", passwordTextBox.Text);
cmd.Parameters.AddWithValue("#EmailAddress", email_AddressTextBox.Text);
cmd.Parameters.AddWithValue("#PhoneNumbers", passwordTextBox.Text);
cmd.CommandText = ("INSERT INTO UserRegiatration VALUES #FirstName, #LastName, #Username, #Password, #EmailAddress, #PhoneNumbers)");
try
{
cnn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You Have Been Registered!");
cnn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("Please Try Again At A Later Time.");
}
}
This is what I have so far but I can't get the information the user enters in the text boxes to post to the database upon the button click event happening.
Any idea what I need to include or remove to improve this?
You missed a (:
INSERT into UserRegiatration VALUES
(#FirstName,#LastName,#Username,#Password,#EmailAddress,#PhoneNumbers)
^
Also, did you mean to write UserRegistration or is the table really called UserRegiatration?
In some cases you should have your table name should be surrounded in brackets.
It would look like:
INSERT into [UserRegiatration] VALUES
(#FirstName,#LastName,#Username,#Password,#EmailAddress,#PhoneNumbers)
I rewrote my tables and did some more research, it turns out, I was missing the part of the statement which identified which specific columns the information was supposed to be inserted into. This is what is now working for me. Thanks for the guidance and the troubleshooting advice.
private void registerButton_Click(object sender, EventArgs e)
{
string connetionString = null;
connetionString = #"Data Source=THANATOS\SQLEXPRESS01;Initial Catalog=LoginDatabase;Integrated Security=True";
try
{
using (SqlConnection connection = new SqlConnection(connetionString))
{
if (connection.State == ConnectionState.Closed) // Checking connection status, if closed then open.
{
connection.Open();
this.Hide();
}
String query = "INSERT INTO dbo.[Table] (FirstName,LastName,Username,Password,Email,PhoneNum) VALUES (#FirstName,#LastName,#Username,#Password,#Email,#PhoneNum)";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#FirstName", firstNameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#LastName", lastNameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Username", usernameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Password", passwordTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Email", emailTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#PhoneNum", phoneNumTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
int result = cmd.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error inserting data into Database!"); // If error, display message.
}
}
}
catch (Exception ex)
{
string v = ex.Message;
throw ex;
}
}
private void phoneNumLabel_Click(object sender, EventArgs e)
{
}
}
}
I got this error and I don't know what I doing wrong. The code below is in the backrgoundworker.
Copy exception detail to the clipboard :
System.Runtime.InteropServices.InvalidComObjectException was unhandled
by user code HResult=-2146233049 Message=COM object that has been
separated from its underlying RCW cannot be used. Source=mscorlib
StackTrace:
at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis)
at System.Data.Common.UnsafeNativeMethods.IAccessor.ReleaseAccessor(IntPtr
hAccessor, Int32& pcRefCount)
at System.Data.OleDb.RowBinding.Dispose()
at System.Data.OleDb.OleDbCommand.ResetConnection()
at System.Data.OleDb.OleDbCommand.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at AttendanceSystem.Student.frmNewStudent.bgwInsertStudent_DoWork(Object
sender, DoWorkEventArgs e) in
c:\Users\victorbaccaljr\Desktop\PROGRAM\Event Attendace
System\AttendanceSystem\AttendanceSystem\Student\frmNewStudent.cs:line
138
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object
argument) InnerException:
code :
private void bgwInsertStudent_DoWork(object sender, DoWorkEventArgs e)
{
List<object> arg = (List<object>)e.Argument;
bool found = false;
using (OleDbConnection cnn = new OleDbConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandText = "select top 1 * from [student info] where id=#id";
cmd.Connection = cnn;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#id", arg[0].ToString());
cnn.Open();
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
if (rdr.HasRows)
{
found = true;
}
cnn.Close();
}
}
using(OleDbCommand cmd=new OleDbCommand())
{
if(found)
{
MessageBox.Show("Student ID already inserted.");
}
else
{
cmd.CommandText = "insert into [Student info] values(#id, #firstname, #lastname, #department, #address)";
cmd.Connection = cnn;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#id", arg[0].ToString());
cmd.Parameters.AddWithValue("#firstname", arg[1].ToString());
cmd.Parameters.AddWithValue("#lastname", arg[2].ToString());
cmd.Parameters.AddWithValue("#department", arg[3].ToString());
cmd.Parameters.AddWithValue("#address", arg[4].ToString());
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
MessageBox.Show("Record inserted!");
this.DialogResult = DialogResult.OK;
}
}
}
}
As Aspirin mentioned in the comment you shouldn´t call Connection.Close on your own. But that´s not a general rule. You´re right that the connection should be closed to free unmanaged resources like a connection to the database or file-handlers. However in your case as you have an enclosing using-block that will automatically call Dipose when the variable gets out of scope and thus will call Connection.Close this latter call is done twice causing the exception when you´re closing the connection yourself.
Your using-block would be similar to this:
OleDbConnection con;
try
{
con = new OleDbConnection(...);
// ...
con.Close();
}
finally
{
if(con != null) con.Close();
}
Causing Close to be called twice on a successful run.
So you can simply omit the call to cnn.Close. because it´s allready done implicietly.
I am trying to save data from web form in visual studio 2015(community edition). I am repeatedly getting error:
no mapping exists from object type. Error at line "com.ExecuteNonQuery()".
I have tried various solutions mention in this forum but none of them work for me. Please help. Thank you.
Error Message:
My code
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [Table] where Username='" + un.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (temp == 0)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertquery = "insert into [Table] (Designation, Username, Email, [Password]) values (#Designation, #Username, #Email, #Password)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.AddWithValue("#Designation", dn.SelectedItem.ToString());
com.Parameters.AddWithValue("#Username", un.Text);
com.Parameters.AddWithValue("#Email", em.Text);
com.Parameters.AddWithValue("#Password", pw.Text);
com.ExecuteNonQuery();
Response.Redirect("Managers.aspx");
Response.Write("Registration Successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("error :" + ex.ToString());
}
}
}
}
Your error seems to be in this line:
com.Parameters.AddWithValue("#Designation", dn.SelectedItem.ToString());
The AddWithValue do a mapping to determine what datatype is the object that you are passing to the method. That is failing.
Try this:
1) com.Parameters.Add("#Designation", SqlDbType.VarChar).Value = dn.SelectedItem.ToString();
2) If you want to keep using AddWithValue debug to see what is inside dn.SelectedItem.ToString()
Anyway, it is always preferable to use Add instead AddWithValue because of that typical problems as the one you are having right now. Take a look at this article: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
As above error it seems due to object typecasting is invalid.
The major difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.
For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).
protected void Button1_Click(object sender, EventArgs e) {
if (temp == 0) {
try {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertquery = "insert into [Table] (Designation, Username, Email, [Password]) values (#Designation, #Username, #Email, #Password)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.Add("#Designation", SqlDbType.VarChar).Value = dn.SelectedItem.ToString();
com.Parameters.Add("#Username", SqlDbType.VarChar).Value = un.Text;
com.Parameters.Add("#Email", SqlDbType.VarChar).Value = em.Text;
com.Parameters.Add("#Password", SqlDbType.VarChar).Value = pw.Text;
com.ExecuteNonQuery();
Response.Redirect("Managers.aspx");
Response.Write("Registration Successful");
conn.Close();
} catch (Exception ex) {
Response.Write("error :" + ex.ToString());
}
}
}
what is the problem in my code?
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";
String kerdes = Convert.ToString(textBox1.Text);
String valaszok = Convert.ToString(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(#kerdes, #valaszok)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#kerdes", OleDbType.VarChar).Value = kerdes;
cmd.Parameters.Add("#valaszok", OleDbType.VarChar).Value = valaszok;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
When I click the button it says:
Microsoft Office Access Database Engine
I made the database with Access. Any ideas?
OleDbCommand does not support named parameters - use ? instead:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.
You need to change your parameters to:
cmd.Parameters.AddWithValue("#kerdes", kerdes);
cmd.Parameters.AddWithValue("#valaszok", valaszok);
This needs to be done in addition to the above comment of changing your query to:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
i write code that insert and delete some data with Microsoft Access database , i can insert the data but when i delete it i have an error "data-type-mismatch-in-criteria-expression" i don't know why !!! Any one help me ?
thanks in advance ;
private void Savebt_Click(object sender, EventArgs e)
{
//try
//{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\me\Library Store\Library Store\Store.accdb");
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Libarary ( ISBN, [Name], Gategory, Author, Cost, [Date]) " +
"VALUES ( #ISBN, #Name, #Gategory, #Author, #Cost, #Date) ";
cmd.Parameters.AddWithValue("#ISBN", ISBNTB.Text);
cmd.Parameters.AddWithValue("#Name", NameTB.Text);
cmd.Parameters.AddWithValue("#Gategory", GategoryTB.Text);
cmd.Parameters.AddWithValue("#Author", AuthorTB.Text);
cmd.Parameters.AddWithValue("#Cost", int.Parse(CostTB.Text));
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Book Added!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void sellbt_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\me\Library Store\Library Store\Store.accdb");
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = " DELETE * FROM Libarary WHERE ISBN=#ISBN AND [Name]=#Name AND Gategory=#Gategory AND Author=#Author AND Cost=#Cost AND [Date]=#Date ";
cmd.Parameters.AddWithValue("#ISBN", ISBNTB.Text);
cmd.Parameters.AddWithValue("#Name", NameTB.Text);
cmd.Parameters.AddWithValue("#Gategory", GategoryTB.Text);
cmd.Parameters.AddWithValue("#Author", AuthorTB.Text);
cmd.Parameters.AddWithValue("#Cost", CostTB.Text);
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Book removed to be sold!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Errow with the record which i try to delete
database records
You are facing this error because one/many parameters that you are passing to your query are of not the same type as it is in the database. Cross check them. and ideally should pass parameters to your query like this
cmd.Parameters.Add("#Date", OleDbType.Date); //note i have specified the db type
cmd.Parameters["#Date"].Value =dateTimePicker1.Value;
this will ensure that you have same types as defined in your database
Try:
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Value);
DateTimePicker.Text returns string representation of selected value, not the value itself.
How about?
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Value.ToString("dd-MM-yyyy"));