Error to convert varchar to float using c# - c#

I have a problem , i'm trying to do operations between values recorded(type float) in table of data , the problem is when i try to update value(result of the operation in textbox) in datable using combobox after maintaining opération , it shows me error (System.Data.SqlClient.SqlException: 'Error converting data type varchar to float.'), So how can i resolve that !help please
This is a part a of my code in which the error exists
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Table_com where Variable='" + comboBox5.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
MessageBox.Show("Variable mise à jour avec succés");
}

You cannot use float integer etc. values like text field as:
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
and your code really risky, you may use parameters like this, dont use string and convert your value to float :
static void Main(string[] args)
{
var ConnectionString = "YOUR CONNECTION STRING";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
String query = "UPDATE Table_com SET Contents=#contents WHERE Variable=#variable";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = Convert.ToDouble(textBox6.Text);
cmd.Parameters.Add("#variable", SqlDbType.NVarChar).Value = comboBox5.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}

this is what i tried refering to wikiCan answer
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-VEFPLGG\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String query = "UPDATE Table_com SET Contents=#contents ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = textBox6.Text;
//cmd.Parameters.Add("#variable", SqlDbType.Float).Value = Convert.ToDouble(comboBox5.Text);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}

Related

c# populating multiple combo box for update and delete question

this combo box gets the job id from the database and assigns it to the jobidcombobox.
private void filljobid()
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT job_id FROM job";
DataSet ds = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(ds);
con.Close();
jobidcombobox.DisplayMember = "job_id";
jobidcombobox.ValueMember = "job_id";
jobidcombobox.DataSource = ds.Tables[0];
}
And then this indexchange code takes the jobidcombobox value and uses it it to query to get the rest of the columns that relate to it.
private void jobidcombobox_SelectedIndexChanged(object sender, EventArgs e)
{
string JobID = jobidcombobox.Text;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * from job where job_id = '" + JobID + "' ";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
customeridcombobox.Text = ds.Tables[0].Rows[0]["customer_id"].ToString();
depotidcombobox.Text = ds.Tables[0].Rows[0]["depot_id"].ToString();
startlocationtextbox.Text = ds.Tables[0].Rows[0]["start_location"].ToString();
endlocationtextbox.Text = ds.Tables[0].Rows[0]["end_location"].ToString();
jobtypecombobox.Text = ds.Tables[0].Rows[0]["job_type"].ToString();
}
else
{
MessageBox.Show("Invalid job number");
}
}
As seen above the customerid is filled but only with a single value which relates to the jobid. I would like to add other customer id values in here from the database. I have tried to same function as jobid to get the customer id but i cant make it relate to the job id.
Is there any way to do this?
Try this...
Fill the job id and customer id boxes.
private void FillJobIdAndCustomerId()
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT job_id, customer_id FROM job";
DataSet ds = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(ds);
con.Close();
var dataRows = ds.Tables[0].AsEnumerable();
jobidcombobox.DisplayMember = "job_id";
jobidcombobox.ValueMember = "job_id";
jobidcombobox.DataSource = dataRows.Select(x=>x.job_id);
customeridcombobox.DisplayMember = "customer_id";
customeridcombobox.ValueMember = "customer_id";
customeridcombobox.DataSource = dataRows.Select(x=>x.customer_id);
}
And then when the a job id is selected...
private void jobidcombobox_SelectedIndexChanged(object sender, EventArgs e)
{
string JobID = jobidcombobox.Text;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * from job where job_id = #jobId";
commandObject.Parameters.AddWithValue("#jobId", JobID);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
customeridcombobox.SelectedIndex = customeridcombobox.FindString(ds.Tables[0].Rows[0]["customer_id"].ToString());
depotidcombobox.Text = ds.Tables[0].Rows[0]["depot_id"].ToString();
startlocationtextbox.Text = ds.Tables[0].Rows[0]["start_location"].ToString();
endlocationtextbox.Text = ds.Tables[0].Rows[0]["end_location"].ToString();
jobtypecombobox.Text = ds.Tables[0].Rows[0]["job_type"].ToString();
}
else
{
MessageBox.Show("Invalid job number");
}
}
Can follow similar pattern for other combo boxes you have (dept, jobtype from your example) if you would like to.
Note: You may have observed that I changed the query building slightly, using SqlParameters. The way it was written in your sample code is a classic case of SQL Injection.

How to filter results in datagridview combobox based on combobox outside datagridview

I am trying to use the datagridview to input multiple data into sql, but I am having a hard time to bind the datagridview combobox to show items based on the selected item in the combobox (supplier), I can't even bind my sql in the datagridview combobox, sorry for being a noob, but I am trying to finish this project. the code below is the code that I use, it is based on individual comboboxes and textbox and not binded on datagridview.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Inventory.Properties;
namespace Inventory
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
SqlConnection conn = new SqlConnection(#"Data Source=MEDIXPC197;Initial Catalog=Inventory;Integrated Security=True");
SqlCommand cd = new SqlCommand();
private void label15_Click(object sender, EventArgs e)
{
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'inventoryDataSet.dbTrans' table. You can move, or remove it, as needed.
this.dbTransTableAdapter.Fill(this.inventoryDataSet.dbTrans);
cc();
cc2();
cc3();
}
public void cc()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Department from tbldept";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Department"].ToString());
comboBox2.Items.Add(dr["Department"].ToString());
}
conn.Close();
}
public void cc2()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select distinct Supplier from tblmaster";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["Supplier"].ToString());
}
conn.Close();
}
public void cc3()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [Transaction] from [tbltransac]";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox4.Items.Add(dr["Transaction"].ToString());
}
conn.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbldept where Department = '" + comboBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataReader dr = cmd.ExecuteReader();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
conn.Close();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbldept where Department = '" + comboBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataReader dr = cmd.ExecuteReader();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
conn.Close();
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
comboBox5.Items.Clear();
foreach (DataRow dr in dt.Rows)
{
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [tbltransac] where [Transaction] = '" + comboBox4.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
conn.Close();
}
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where ProductCode = '" + comboBox5.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox3.Text = dr["Description"].ToString();
textBox4.Text = dr["UM"].ToString();
textBox5.Text = dr["UP"].ToString();
}
conn.Close();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
EDIT:
Picture below shows my design, I want to filter what will show in Item Code combobox inside the datagridview based on the Supplier combobox
PHOTO

Why won't my simple C# website UPDATE to db using GridView?

I have the following C# to UPDATE a record, however the textbox shows, but doesn't update to the database. Likewise, I cannot ADD a record either.
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
Add:
protected void AddNewMainPost(object sender, EventArgs e)
{
string postID = ((TextBox)GridView1.FooterRow.FindControl("txtPostID")).Text;
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtSelect")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
"values(#postID, #selectionText,);" +
"select postID,selectionText, from homepageSelection";
cmd.Parameters.Add("#postID", SqlDbType.VarChar).Value = postID;
cmd.Parameters.Add("#selectionText", SqlDbType.VarChar).Value = Name;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Update
protected void UpdateMainPost(object sender, GridViewUpdateEventArgs e)
{
string postID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblpostID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSelec")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update homepageSelection set selectionText=#selectionText, " +
"where postID=#postID;" +
"select postID,selectionText from homepageSelection";
cmd.Parameters.Add("#postID", SqlDbType.VarChar).Value = postID;
cmd.Parameters.Add("#selectionText", SqlDbType.VarChar).Value = Name;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
I have two fields in the database:
Table: homepageSelection Fields: postID and selectionText
As I can see from your code above, you have a syntax error in both queries, but most important thing is the fact that you don't associate your command to the connection. Thus, unless you recreate the connection inside the GetData method, your command cannot be executed.
So, to fix the syntax errors
"select postID,selectionText from homepageSelection";
^^^ comma not valid here
cmd.CommandText = #"update homepageSelection set
selectionText=#selectionText" +
^^^^ again comma not valid here
cmd.CommandText = "insert into homepageSelection(postID, selectionText) " +
"values(#postID, #selectionText);" +
^^^ no comma here
EDIT: it seems that you create the connection inside the GetData method, thus you don't need it in the two calling methods.

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

MS Access database not updating

Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video

Categories

Resources