I'm inserting records and one of my object is combobox. The combox is connected to the table. When i'm inserting this error appear:
Failed to convert parameter value from a DataRowView to a Int32
My code:
cn.Open();
SqlCommand Insert = new SqlCommand();
Insert.Connection = cn;
Insert.CommandType = CommandType.Text;
Insert.CommandText = "INSERT INTO Ticket VALUES (CustomerID, Date, Store, Amount, NoStub) ";
Insert.Parameters.Add("CustomerID", SqlDbType.Int).Value = cboName.SelectedValue;
Insert.Parameters.Add("Date", SqlDbType.DateTime).Value = dtpDate.Value.Date.ToString();
Insert.Parameters.Add("Store", SqlDbType.NVarChar).Value = txtStore.Text;
Insert.Parameters.Add("Amount", SqlDbType.Decimal).Value = txtAmount.Text;
Insert.Parameters.Add("NoStub", SqlDbType.Decimal).Value = txtStub.Text;
Insert.ExecuteNonQuery();
cn.Close();
Use this sample code:
command.Parameters.Add("#CustomerID", SqlDbType.Int).Value = Convert.ToInt32(storeCode);
or use
int.parse for cboName.
Change your code to the following and let the Server resolve the data type
cn.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = cn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)
VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
sqlCmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
sqlCmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
sqlCmd.Parameters.AddWithValue("#Store", txtStore.Text);
sqlCmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
sqlCmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
sqlCmd.ExecuteNonQuery();
cn.Close();
Related
The problem is am getting an exception error that says data mismatch in the external database when i try to insert
I have a customer booking table with booking id ...pk as auto number, customer.... fk and date in as datetime
Booking id is auto increment so i don't need to insert anything
What i want to achieve is to insert into customer_id and date in thats all but i keep getting the data mismatch and number of query valuesis not the same as destination fields
So what is the right way to put this
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (?,?)";
cmd.Parameters.AddWithValue("#customer_id", txtusername.Text);
cmd.Parameters.AddWithValue("#date_in", dtdate_in);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
use cmd.Parameters.add('...') method as follow :
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (#customer_id,#date_in)";
///* Set your column dataType*/
cmd.Parameters.Add("#customer_id", SqlDbType.VarChar , 50).Value = txtusername.Text;
cmd.Parameters.Add("#date_in", SqlDbType.DateTime).Value = dtdate_in;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
I have creates a database and I am trying to INSERT INTO TABLE with the following code:
string sqlquery = "INSERT INTO Runner VALUES (#firstName, #lastName, #amount, #category, #city, #charity, #route)";
cmd = new SqlCommand(sqlquery, conn);
conn.Open();
cmd.Parameters.AddWithValue("#firstName", txtFirstName.Text.ToString());
cmd.Parameters.AddWithValue("#lastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#amount", Convert.ToInt32(txtMoney.Text));
cmd.Parameters.AddWithValue("#category", cbBoxCategory.ValueMember);
cmd.Parameters.AddWithValue("#city", cbBoxCity.ValueMember);
cmd.Parameters.AddWithValue("#charity", cbBoxCharity.ValueMember);
cmd.Parameters.AddWithValue("#route", cbBoxRoute.ValueMember);
cmd.ExecuteNonQuery();
conn.Close();
When I run it, I get this error:
System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'id' to data type int.'
All my cbBox (comboBox) need to leave a INT, I understand that is need to convert to NVARCHAR to INT, I try to use Convert.Into32(cbBox.Category.ValueMember) but without success.
I have tried everything with no success.
After looking for other people answer I find this solution.
string sqlquery = "INSERT INTO Runner (firstName, lastName, amount, categoryID, cityID, charityID, routeID) VALUES (#firstName, #lastName, #amount, #category, #city, #charity, #route)";
cmd = new SqlCommand(sqlquery, conn);
conn.Open();
cmd.Parameters.Add("#firstName", SqlDbType.VarChar, 50).Value = txtFirstName.Text;
cmd.Parameters.Add("#lastName", SqlDbType.VarChar, 50).Value = txtLastName.Text;
cmd.Parameters.Add("#amount", SqlDbType.Int).Value = txtMoney.Text;
cmd.Parameters.Add("#category", SqlDbType.Int).Value = cbBoxCategory.SelectedValue;
cmd.Parameters.Add("#city", SqlDbType.Int).Value = cbBoxCity.SelectedValue;
cmd.Parameters.Add("#charity", SqlDbType.Int).Value = cbBoxCharity.SelectedValue;
cmd.Parameters.Add("#route", SqlDbType.Int).Value = cbBoxRoute.SelectedValue;
cmd.ExecuteNonQuery();
MessageBox.Show("New Runner has been registered!");
conn.Close();
By using Convert.ToInt32(cbBoxRoute.SelectedValue)
Here is the link where I find my solution:
Insert ID into SQL from C# Combo box
i tried to saved a value in DB, but when i make the insert, the DB don`t save any data from texbox when they texbox is load from a javascript, this is my insert:
ConectarBD();
Tabb = new SqlCommand("Insert into peliculas Values(#nombre_pelicula,#dias_arriendo,#valor_dia,#total_arriendo,#descuento,#total_pagar) ", Conn);
Dadap.InsertCommand = Tabb;
Dadap.InsertCommand.Parameters.Add("#nombre_pelicula", SqlDbType.VarChar);
Dadap.InsertCommand.Parameters.Add("#dias_arriendo", SqlDbType.VarChar);
Dadap.InsertCommand.Parameters.Add("#valor_dia", SqlDbType.VarChar);
Dadap.InsertCommand.Parameters.Add("#total_arriendo", SqlDbType.VarChar);
Dadap.InsertCommand.Parameters.Add("#descuento", SqlDbType.VarChar);
Dadap.InsertCommand.Parameters.Add("#total_pagar", SqlDbType.VarChar);
Dadap.InsertCommand.Parameters["#nombre_pelicula"].Value = txtNombrePelicula.Text;
Dadap.InsertCommand.Parameters["#dias_arriendo"].Value = txtNumDias.Text;
Dadap.InsertCommand.Parameters["#valor_dia"].Value = txtValorDia.Text;
Dadap.InsertCommand.Parameters["#total_arriendo"].Value = lblTotalArriendo.Text;
Dadap.InsertCommand.Parameters["#descuento"].Value =txtDescuento.Text;
Dadap.InsertCommand.Parameters["#total_pagar"].Value = txtTotalPagar.Text;
Dadap.InsertCommand.ExecuteNonQuery();
lblMensaje.Text = "Datos Grabados";
Conn.Close();
Limpiar();
txtRut.Focus();
Your insert looks wrong, try the following code and change column1,2,3... to columns names in your database.
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "INSERT Into peliculas (Column1, Column1,Column2,Column3,Column4,Column5,Column6) Values(#nombre_pelicula,#dias_arriendo,#valor_dia,#total_arriendo,#descuento,#total_pagar)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#nombre_pelicula", txtNombrePelicula.Text);
cmd.Parameters.AddWithValue("#dias_arriendo", txtNumDias.Text);
cmd.Parameters.AddWithValue("#valor_dia", txtValorDia.Text);
cmd.Parameters.AddWithValue("#total_arriendo", lblTotalArriendo.Text);
cmd.Parameters.AddWithValue("#descuento", txtDescuento.Text);
cmd.Parameters.AddWithValue("#total_pagar", txtTotalPagar.Text);
}
cmd.ExecuteNonQuery();
I want to Insert record to the database with a ComboBox. The ComboBox is connected to the other table and this is the error:
Error converting data type nvarchar to numeric.
private void InsertReceipt()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" +
"VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
cmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
cmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
cmd.Parameters.AddWithValue("#Store", txtStore.Text);
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
cmd.ExecuteNonQuery();
}
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname + ', ' + lastname AS Name FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.Name";
cboName.ValueMember = "Customer.CustomerID";
}
When you call AddWithValue make sure that the type of data you are passing matches the column type. Here's a likely candidate:
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
In this line you are passing a text string to something that clearly wants a numeric value (an amount). You should parse the txtAmount.Text into a decimal first and then pass that value:
decimal amount = decimal.Parse(txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", amount);
With this code, you may still get an exception if the string in txtAmount.Text can't be parsed into a decimal, but at least then you'll know which value is causing the problem. You can/should do the same with the other values as well to make sure they match their column types.
try string.isNullorEmpty(txtAmount.text);
private void button1_Click(object sender, EventArgs e)
{
string sql;
sql = "insert into slab (date,sober_visor,tesh,shift,group,heat_no,st_grade,thick,width,length,location,pcs,remarkes,slab_no) values (#date,#sober_vsor,#tesh,#shift,#group,#heat_no,#st_grade,#thick,#width,#length,#loction,#pcs,#slab_no);select scope_identity()";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#date", txt_date.Text);
cmd.Parameters.AddWithValue("#sober_visor", com_sober_visor.ToString());
cmd.Parameters.AddWithValue("#shift", txt_shift.Text);
cmd.Parameters.AddWithValue("#heat_no", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#thick", txt_shift.Text);
cmd.Parameters.AddWithValue("#width", txt_heat_no.Text);
cmd.Parameters.AddWithValue("#length", txt_length.Text);
cmd.Parameters.AddWithValue("#pcs", txt_pcs.Text);
cmd.Parameters.AddWithValue("#st_grade", txt_st_gread.Text);
cmd.Parameters.AddWithValue("#location", txt_loction.Text);
cmd.Parameters.AddWithValue("#slab_no", txt_slab_no.Text);
con.Open();
cmd.ExecuteNonQuery();
txt_heat_no.Text = cmd.ExecuteScalar().ToString();
con.Close();
MessageBox.Show("تمت عملية الإضافة");
}
}
}
cmd.Parameters.AddWithValue("#ödenecektutar", Convert.ToDecimal(tutar1.Text.Substring(0, tutar.Text.Length - 1)));
I have a text box that is filled with date(date type) from a date picker.
I have a table with 3 columns(name,fromdate(date),todate(date)). On button click activity it should show only those names which have the date specified between the from date and to date.
I would like some help me on this
string v = System.Configuration.ConfigurationManager.ConnectionStrings["harish"].ConnectionString;
con = new OracleConnection(v);
con.Open();
cmd = new OracleCommand("________", con);
You're not even trying. Try Oracle and MSDN for this.
But since you're in a jam....
var cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table (name, fromDate, toDate)VALUES(:nameVal, :fromVal, :toVal)";
cmd.Parameters.Add(new OracleParameter(":fromVal", OracleType.DateTime)).Value = fromDateVal;
cmd.Parameters.Add(new OracleParameter(":toVal", OracleType.DateTime)).Value = toDateVal;
cmd.ExecuteNonQuery();
//close the connection after done.... release the resources