Get error at com.ExecuteNonQuery() while adding data into table - c#

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

Related

System.Threading.ThreadAbortException: Thread was being aborted.

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.

Inserting Data From C# Form Into Linked Database?

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)
{
}
}
}

How can I insert and save data into database using Visual Studio and C#?

public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can I insert and save data into the database using Visual Studio and C#?
This code throws an error. Anyone please give the suggestion to me to solve the error.
image description
At first make sure your the data type of different column of customer table.
Then make sure what type of data you have to save for combobox.
you have to get the selected value from your Combobox. combobox1,combobox2,combobox3 retuns only the class name
System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
You can follow this example
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query):
Specifically, you don't need a reader for an insert statement as it doesn't return a result set.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var sql = "insert into dbo.customer ...";
using (var con = new SqlConnection(ss))
{
var cmd = new SqlCommand(sql , con);
con.Open();
cmd.ExecuteScalar();
MessageBox.Show("Welcome to our gym");
}
}
Hi check that customer table is available in gym Database.
else try this link
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(#name,#weight,#height,#add_class,#gender,#fees)", con);
cmd.Parameters.AddWithValue("name", this.textBox1.Text);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I found that your connection string declaration is wrong
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
need to update like below
public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";
Data source will be not be D, It should be Server name.
enter image description here

data-type-mismatch-in-criteria-expression-error when delete from MS Access with ADO.NET C#

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"));

Stored Procedure ADO.NET error

Hello I have a Stored Proc for the Registration Page, but I need ADO.NET to take values from various textboxes.
However, I'm recieving error like this:
"System.ArgumentException: No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type. "
public void InsertInfo()
{
String empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(empdb);
SqlCommand cmd = new SqlCommand("bridge_Type", conn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("#Name", TextBox2.Text));
cmd.Parameters.Add(new SqlParameter("#Mob2", TextBox3.Text));
cmd.Parameters.Add(new SqlParameter("#Email", TextBox14.Text));
cmd.Parameters.Add(new SqlParameter("#Emptype", dropdown1.SelectedValue));
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertInfo();
}
Then I used this format to add values from controls:
cmd.Parameters.Add(new SqlParameter("#EmpID", SqlDbType.Int));
cmd.Parameters("#EmpID").Value = TextBox1.Text;
I'm getting errors on:
Its showing errors for these kind of codes by appearing red line under 'Parameters'.
Non-invocable member 'System.Data.SqlClient.SqlCommand.Parameters' cannot be used like a method.
Try TextBox1.Text, TextBox is the Control. The Text property holds the String value.
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
Try this code.
try
{
string empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand("bridge_Type",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpID",TextBox1.Text);
cmd.Parameters.AddWithValue("#Name", TextBox2.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox3.Text);
cmd.Parameters.AddWithValue("#Email", TextBox14.Text);
cmd.Parameters.AddWithValue("#EmpType",dropdown1.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
string msg = "Insert Error:"+ ex.Message;
throw new Exception(msg);
}
Make sure you are converting to the types same as the Parameter types in your stored proc ( Ex: If the parameter type of EmpID is int, you may need to convert the TextBox1.Text value to int. Check for null values also.
why dont u use this format?
cmd.Parameters.Add("#parameter", SqlDBType , size).value = TextBox1.Text

Categories

Resources