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
Related
I'm able to delete, insert and update in my program and I try to do an insert by calling a created stored procedure from my database.
This button insert I made works well.
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (#FirstName, #LastName)", con);
da.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
da.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
This is the start of the button that calls the procedure named sp_Add_contact to add a contact. The two parameters for sp_Add_contact(#FirstName,#LastName). I searched on google for some good examples but found nothing interesting.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
cmd.CommandType = CommandType.StoredProcedure;
???
con.Open();
da. ???.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.
Also, use a using for all disposable objects, so that you are sure that they are disposed properly:
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
You have to add parameters since it is needed for the SP to execute
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", txtfirstname.Text);
cmd.Parameters.AddWithValue("#LastName", txtlastname.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
cmd.Parameters.Add(String parameterName, Object value) is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason they
deprecated the cmd.Parameters.Add(String parameterName, Object value) in favor of AddWithValue(String parameterName, Object value) is to give more
clarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
sqlAccess.Procedure()
.AddSqlParameter("#FirstName", SqlDbType.VarChar, txtFirstName.Text)
.AddSqlParameter("#FirstName", SqlDbType.VarChar, txtLastName.Text)
.ExecuteNonQuery("StoredProcedureName");
public void myfunction(){
try
{
sqlcon.Open();
SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlcon.Close();
}
}
The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
#COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = #COUNTRY
GO
The above stored procedure is accepting a country name (#COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("#COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("#COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money
public void SaveTransaction(Transaction transaction)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (var cmd = new SqlCommand("spAddTransaction", con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
cmd.Parameters.AddWithValue("#" + prop.Name, prop.GetValue(transaction, null));
con.Open();
cmd.ExecuteNonQuery();
}
}
}
I have got an error that you must have to declare a static variable #campus_id. I don't know how to declare and where to declare and what it means to declare a static variable. Help me please!
private void btnSave_Click(object sender, EventArgs e)
{
try
{
CS = ConfigurationManager
.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ISNULL(MAX(campus_id),0)+1 FROM Campus", con);
cmd.CommandType = CommandType.Text;
tbCampusID.Text = cmd.ExecuteScalar().ToString();
using (SqlCommand cmd1 = new SqlCommand(
"INSERT INTO Campus (campus_id,campus_name)VALUES(#camp_id,camp_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#campus_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("#campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Saved");
}
}
}
catch (Exception)
{
}
}
The parameter names in your SQL query and in the call to Parameters.AddWithValue must match:
using (SqlCommand cmd1 = new SqlCommand(
"INSERT INTO Campus (campus_id, campus_name) VALUES(#campus_id, #campus_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#campus_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("#campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
}
You are adding value to a placeholder that is not yet defined. see this statement
cmd1.Parameters.AddWithValue("#campus_id", tbCampusID.Text); Here you are using campus_id as placeholder and take a look into the insert query, ie., INSERT INTO Campus (campus_id,campus_name)VALUES(#camp_id,camp_name). and there the placeholder is camp_id and that causing the error; use like this:
string querySql = "INSERT INTO Campus (campus_id, campus_name) VALUES(#camp_id, #campus_name)"
using (SqlCommand cmd1 = new SqlCommand(querySql, con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#camp_id", tbCampusID.Text);
cmd1.Parameters.AddWithValue("#campus_name", tbCampusName.Text);
cmd1.ExecuteNonQuery();
con.Close();
}
I'm trying to execute a stored procedure and print the output, but when I run the below code I'm getting error like "Procedure or function 'SPInsertLocal' expects parameter '#RES', which was not supplied."
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type", con);
try
{
con.Open();
cmd.CommandTimeout = 150;
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
SqlParameter output = new SqlParameter("#RES", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
con.Close();
int id = Convert.ToInt32(output.Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
What I'm doing wrong here?
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type,#RES", con);
I was not passing the parameter , fixed the issue
You can refactor the code as follows where the using statement is used for the auto management of connection closing and avoid hardcoding Execute statement in c# code which is a bad practice
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
try
{
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
var output = cmd.Parameters.Add("#RES" , SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int id = Convert.ToInt32(output.Value);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is my code for the insert, I got textboxes on my form and I write something inside but when pressing the button with executes the code below it shows an error by the (cmd.ExecuteNonQuery)
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype, patribute, role, role2, role3) VALUES (#Heroname, #Attacktype, #patribute, #role, #role2, #role3)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#Attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
textBox1.Clear(); textBox2.Clear();
textBox3.Clear(); textBox4.Clear();
textBox5.Clear(); textBox6.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
The second code snippet is my update code which shows same an error when trying to execute, same error by the execute non query
SqlDataReader reader = null;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
SqlCommand sda = new SqlCommand("SELECT * FROM Heroes ", cn);
cn.Open();
reader = sda.ExecuteReader();
while (reader.Read())
{
object Heroname = reader["heroname"];
listBox1.Items.Add(Heroname.ToString());
}
reader.Close();
cn.Close();
Please I need help and as quick as someone can, ty!
I think you receive this error, that because you using reserved word Role you should place It in brackets [].
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype,patribute,[role],role2,role3) VALUES (#Heroname, #Attacktype,#patribute,#role,#role2,#role3)";
I suggest to avoid that method of passing parameters, with
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
you didn't specify datatype and length, that's correct ADO.NET will guess them but this is not happens always, instead of that try this method:
cmd.Parameters.Add("#Heroname", SqlDbType.VarChar, 50).Value = textBox1.Text;
for all of your parameters.
Was it a null reference exception?
Reading your code, I think you need to change SqlDataReader reader = null; to SqlDataReader reader = new SqlDataReader;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
SqlCommand cmd = new SqlCommand("INSERT INTO Heroes (heroname,attacktype,patribute,role,role2,role3) Values (#heroname,#attacktype,#patribute,#role,#role2,#role3) ", cn);
cn.Open();
cmd.Parameters.AddWithValue("#heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
This code worked now, inside my form i added a listbox and it does show the added row with its values! But closing form and checking inside database, it doesnt show that row? Whats wrong?
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"));