System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.' Grid view update - sql

I am working on a grid view update but System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression error. Please someone help.
protected void ResultGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtFName2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtFName");
TextBox txtDate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtSM");
TextBox txtCaseType2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCaseType");
TextBox txtFileno2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtFileno");
TextBox txtCustName2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCustName");
TextBox txtAddress2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCustName");
TextBox txtConno2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtConno");
TextBox txtPlotarea2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotarea");
TextBox txtPlotRate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotRate");
TextBox txtconstarea2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstarea");
TextBox txtConstFloor2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtConstFloor");
TextBox txtconstrate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstrate");
TextBox txtPlotvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotvalue");
TextBox txtconstvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstvalue");
TextBox txttotalvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txttotalvalue");
TextBox txtRemarks2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtRemarks");
**TextBox txtDatee2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtDate2");**
string da = txtDatee2.Text.ToString();
DateTime dt =
DateTime.ParseExact(da, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
string dateshort = dt.ToShortDateString();
string ID = ResultGridView.DataKeys[e.RowIndex].Values[0].ToString();
cmd.Connection = conn;
cmd.CommandText = "UPDATE Final SET Finance ='" + txtFName2.Text + "' ,SM ='" + txtDate2.Text + "',Case_Type ='" + txtCaseType2.Text + "',File_no ='" + txtFileno2.Text + "',Cust_Name ='" + txtCustName2.Text + "' ,Address ='" + txtAddress2.Text + "',Con_no ='" + txtConno2.Text + "' ,Plot_area ='" + txtPlotarea2.Text + "' ,Plot_Rate ='" + txtPlotRate2.Text + "' ,const_area ='" + txtconstarea2.Text + "' ,Const_Floor ='" + txtConstFloor2.Text + "' ,const_rate ='" + txtconstrate2.Text + "' ,Plot_value ='" + txtPlotvalue2.Text + "' ,const_value ='" + txtConno2.Text + "' ,total_value ='" + txttotalvalue2.Text + "' ,Remarks ='" + txtRemarks2.Text + "'**,Date2 = '"+ dateshort +"'** WHERE ID=" + ID + "";
conn.Open();
cmd.ExecuteNonQuery();
ResultGridView.EditIndex = -1;
FillVendorGrid();
conn.Close();
}

At least, first text expressions for date values should be formatted as to the ISO sequence:
string dateshort = dt.ToString("yyyy'/'MM'/'dd");
second, in Access, these must be wrapped in octothorpes:
"', Date2 = #" + dateshort + "# WHERE ID="
This must be modified for other datetime fields as well.
Or, do your self a big favour and turn to call a parameterised query.

Related

How to update the data of the selected row in datagridview?

This is my code:
SqlConnection connection = new SqlConnection(global::Registro_Elettronico_Reperti.Properties.Settings.Default.Registro_RepertiConnectionString);
string sql = "UPDATE Registro_Reperti SET [Ritirato da]='" + cbox_competenza.Text + "', Operatore='" + txt_operatore.Text + "', PerID= '" + txt_perid + "', Ritirato = 'Si' WHERE Id=?????";
System.Data.SqlClient.SqlCommand exeSql = new System.Data.SqlClient.SqlCommand(sql, connection);
connection.Open();
exeSql.ExecuteNonQuery();
MessageBox.Show("Operazione completata", "Messaggio", MessageBoxButtons.OK, MessageBoxIcon.Information);
How to get the id of the row in the WHERE clause??

DataGridView sorts dates in wrong order

I have a DataGridView and a searchbox where I can search for different dates in a certain column. Now since the date is formated as string he will give me the wrong order:
I type in 20 and get:
20.10.2014,
22.09.2014,
24.11.2014
and so on. I have read another thread here about this problem but the solutions didn't help me. My SQL statement looks like following:
DataTable datTable = new DataTable();
sqlCmd = new SqlCommand("SELECT ["+form1.timeBox.Text+ "] FROM [" + form1.getTableName() + "] WHERE convert(varchar(10),[" + form1.getTimeCol() + "],104) >= '" + form1.getFromDate().Trim() + "' ORDER BY convert(varchar(10),[" + form1.getTimeCol() + "],104) ASC", connection);
sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText, connection);
sqlDatAdapter.Fill(datTable);
form1.setDataGrid = datTable;
and
form1.getFromDate()
is the function which grabs the entered string from the Textbox to search for. I tried to cast and convert to datetime and so on but it gets still shown in the wrong order. Can anyone help?
you are ordering by the formatted column; there is no need to do so and that is the part creating your problem.
i'm against string concatenation to build sql commands but your code should be rewritten as follows:
sqlCmd = new SqlCommand("SELECT ["+form1.timeBox.Text+ "] FROM [" + form1.getTableName() + "] WHERE convert(varchar(10),[" + form1.getTimeCol() + "],104) >= '" + form1.getFromDate().Trim() + "' ORDER BY " + form1.getTimeCol() + " ASC", connection);
nstead of using '>=' use 'Like' operator with '%' character at the end of your "form1.getFromDate().Trim()", which will give you the required result.
Using 'Like' your query will look like:
sqlCmd = new SqlCommand("SELECT ["+form1.timeBox.Text+ "] FROM [" + form1.getTableName() + "] WHERE convert(varchar(10),[" + form1.getTimeCol() + "],104) Like '" + form1.getFromDate().Trim() + "%' ORDER BY convert(varchar(10),[" + form1.getTimeCol() + "],104) ASC", connection);

SQL unable to cast object of type 'system.string' to type 'system.iformatprovider' error in vb.net

I am trying to run this Query in my VB Application but receive an error saying:
unable to cast object of type 'system.string' to type 'system.iformatprovider'
SQL = "insert into billing_pdf_archive (reseller_sequence, invoice_number, pdf, worddoc, csv_cdr_file, csv_services_file, sub_total, vat_amount, grand_total, invoice_type, directdebit) values ('" + reseller.ToString + "','" + invoice_number.ToString + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".pdf", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".doc", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_CDR.xlsx", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_Services.xlsx", " ", "_") + "', " + total.ToString("F2") + ", " + vat_amount.ToString("F2") + ", " + grand_total.ToString("F2") + ", 'Month End Reseller', '" + customer_direct_debit + "')"
conn3.ConnectionString = "server=" + global_variables.web_server_ip + "; user id=" + global_variables.web_server_username + "; password=" + global_variables.web_server_password + "; database=" + global_variables.web_server_database + "; "
conn3.Open()
myCommand3.Connection = conn3
myCommand3.CommandText = SQL
myCommand3.ExecuteNonQuery()
conn3.Close()
This is not a complete answer but I'll post it as an answer so that I can post formatted code. If you do as suggested in the comments and write clean, readable code then it will become obvious where the issue is and how to fix it. When you have one line that does lots of different things then working out what on that line is causing an issue is all but impossible. You should use an XML literal for your SQL code, parameters for your values and a connection string builder, e.g.
Dim sql = <sql>
INSERT INTO MyTable
(
Column1,
Column2
)
VALUES
(
#Column1,
#Column2
)
</sql>
command.CommandText = sql.Value
command.Parameters.AddWithValue("#Column1", value1)
command.Parameters.AddWithValue("#Column2", value2)
Dim builder As New SqlConnectionStringBuilder
builder.DataSource = server
builder.InitialCatalog = database
connection.ConnectionString = builder.ConnectionString
Now you'll be able to see exactly what part of your code is causing the issue and, if you still can't solve it yourself, will be able to point out where the issue is to us instead of expecting us to read that dog's breakfast.

Can't add particular values to the database

So I'm currently having a problem where I can't seem to add values to my sql-database. I'm constantly getting sql error 104. Saying that some tokens are unknown.
try{
//The part below gets the employee-ID and the names of the skill I want to add to him/her.
String valdAnstalld = jComboBoxUppKompVal.getSelectedItem().toString();
String nyKomp = jComboBoxUppKID.getSelectedItem().toString();
String nyP = jComboBoxUppPF.getSelectedItem().toString();
String nyNiva = jComboBoxUppNiva.getSelectedItem().toString();
//This part takes the name of the skill, and gets its ID-number.
String KompID = "select kid from kompetensdoman where benamning = '" + nyKomp + "'";
String PlattID = "select pid from plattform where benamning = '" + nyP + "'";
//And finally this part is supposed to insert the ID-numbers into the "has_competance" table.
String sqlUppKomp = "insert into har_kompetens VALUES " + "(" + valdAnstalld + ", '"
+ KompID + "', '" + PlattID + "', '" + nyNiva + "' where aid = '" + valdAnstalld + "')";
idb.insert(sqlUppKomp);
JOptionPane.showMessageDialog(null, "Tillagd!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
uppdateraKomp();

string concatation in sql query

i am having confusion with this string concatenation
could some body please brief me how this string concatenation taking place?
The confusion i am having is that, how this +, "", ' are working in this
int i = Magic.Allper("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Anything between two " characters is taken as a String in Java so "','" produces ','. SQL requires Strings wrapped in '. So "'" + venueTxt.Text + "'" parses to 'variable value' when the query is made.
("insert into tbl_notice values ('" + Label1.Text + "','" + companyTxt.Text + "','" + txtBranch.Text + "','" + dateTxt.Text + "' ,'" + reportingTxt.Text + "','" + venueTxt.Text + "','" + eligibilityTxt.Text + "')");
Assuming that
Label1= Hello
companyTxt = ABC
txtBranch = Engineering
dateTxt = 2010-12-01
reportingTxt = Fergusson
venueTxt = Batcave
eligibilityTxt = No
The above values are replaced in the SQL statement, making it look like
("insert into tbl_notice values ('" + Hello + "','" + ABC + "','" + Engineering + "','" + 2010-12-01 + "' ,'" + Fergusson + "','" + Batcave + "','" + No + "')");
The "+" operator joins the string values, resulting in
("insert into tbl_notice values ('Hello','ABC','Engineering','2010-12-01' ,'Fergusson','Batcave','No')")
I strongly recommend that you don't use string concatenation in SQL queries. They provoque SQL injections. This will cause security issues.
What is SQL Injection?
In response to your question, this concatenation simply takes every TextBox.Text property value and concatenate it into your insert statement.
I strongly recommend that you're using parameterized queries using ADO.NET lise the following example (assuming SQL Server):
using (var connection = new SqlConnection(connString))
using (var command = connection.CreateCommand()) {
string sql = "insert into tbl_notice values(#label1, #companyTxt, #txtBranch, #dataTxt, #reportingTxt, #venueTxt, #eligibilityTxt)";
command.CommandText = sql;
command.CommandType = CommandType.Text;
SqlParameter label1 = command.CreateParameter();
label1.ParameterName = "#label1";
label1.Direction = ParameterDirection.Input;
label1.Value = Label1.Text;
SqlParameter companyTxt = command.CreateParameter();
companyTxt.ParameterName = "#companyTxt";
companyTxt.Direction = ParameterDirection.Input;
companyTxt.Value = companyTxt.Text;
// And so forth for each of the parameters enumerated in your sql statement.
if (connection.State == ConnectionState.Close)
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
I would use the string.Format method for clarity
int i = Magic.Allper(string.Format("insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));
You might also want to create an extension method that will make sure the strings are safe to pass to SQL in this fashion
public static string ToSqlFormat(this string mask, params string[] args)
{
List<string> safe = args.ToList();
safe.ForEach(a => a.Replace("'", "''"));
return string.Format(mask, safe);
}
which will let you write
string insert = "insert into tbl_notice values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
int i = Magic.Allper(insert.ToSqlFormat(
Label1.Text,
companyTxt.Text,
txtBranch.Text,
dateTxt.Text,
reportingTxt.Text,
venueTxt.Text,
eligibilityTxt.Text));