Sql query added to title? - sql

In c# Windows Forms:
I'm having trouble adding a sql query result as text to a ToolStripMenuItem.Text.
The ToolStripMenuItem title should be, the company + how many orders there are in the sql table for this company which should update every x secounds.
Every 5 seconds it adds the query result to the text. My problem is that is "adds" it.
After the first 5 seconds it looks OK "rexton 1" but 5 seconds after it shows "rexton 1 1" and so on...
Here is my code:
//Rexton ordre klar til bestilling
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE firma = #rexton and udlevering BETWEEN #date and #dateadd";
command.Parameters.AddWithValue("#bernafon", "Bernafon");
command.Parameters.AddWithValue("#gn_resound", "GN Resound");
command.Parameters.AddWithValue("#oticon", "Oticon");
command.Parameters.AddWithValue("#phonak", "Phonak");
command.Parameters.AddWithValue("#rexton", "Rexton");
command.Parameters.AddWithValue("#siemens", "Siemens");
command.Parameters.AddWithValue("#widex", "Widex");
con.Open();
command.ExecuteNonQuery();
string result = command.ExecuteScalar().ToString();
con.Close();
if (result != "0")
{
rextonToolStripMenuItem.Text = rextonToolStripMenuItem.Text + " " + result;
rextonToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}

it is because you are setting rextonToolStripMenuItem.Text to rextonToolStripMenuItem.Text + " " + result which is appending to previous text
either set text to blank and set it again or just say
rextonToolStripMenuItem.Text = "rexton " + result

Related

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

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.

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??

MS SQL Invalid column name error

This code returns the following error:
"System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'a51'"
a51 is the correct value inside of the record I'm looking for in the EstablishmentCode column of the Establishments table. Account ID is used to find all entries on the Establishments table with that account ID and populate a dataset with Establishment Code values. Account ID value comes from a session variable. Then I use each of these values in a loop where each iteration calls a datareader while loop. Hope I explained this clearly, but I would gladly clarify more if needed. Here's my code.
myConnection.Open();
SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection);
da = new SqlDataAdapter(getEst);
ds = new DataSet();
da.Fill(ds);
int maxrows = ds.Tables[0].Rows.Count;
for (int x = 0; x < maxrows; x++)
{
getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection);
myReader = getPhones.ExecuteReader();
while (myReader.Read())
{
Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>");
Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>");
Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>");
Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>");
Response.Write("<section class='flex phoneButtonSection'>");
Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>");
Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>");
Response.Write("</section>");
Response.Write("</section>");
}
myReader.Close();
}
myReader.Close();
myConnection.Close();
String literals in SQL are denoted by single quotes ('s) which are missing for your value:
getPhones = new SqlCommand
("SELECT * " +
"FROM DispatcherPhones
"WHERE EstablishmentCode = '" +
// Here -------------------^
ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString() +
"'" // And here
, myConnection);
Mandatory comment: concatinating strings in order to create SQL statements may leave your code exposed to SQL injection attacks. You should consider using prepared statements instead.

Mistakenly inserted date in month field sql how to change

Unfortunately I inserted a date as dd-mm-yyyy in sql but it assumed it as mm-dd-yyyy Now more than 50 fields are like this how can I change this? I found an exception as invalid date when I was taking report by date that more than 12. Now I want to change all of the inserted fields without losting it
UPDATE tableName
SET dateColumn = MONTH(dateColumn) + "-" + DAY(vdateColumn) + "-" + YEAR(dateColumn)
I hope this work even though I didn't test it myself. Please use a WHERE clause to limit the update only to the impacted rows.
UPDATE yourTable
SET yourDateColumn = Convert(datetime,yourDateColumn,101)
Let me know if this fixes your issue.
Nothing worked but finally I reset it manually by c# console
Console.WriteLine("Changing Orderdate");
Console.WriteLine("~~~~~~~~~~~~~~~~~~");
List<string> date = new List<string>();
List<string> no = new List<string>();
int i = 0;
SqlCommand cmd = new SqlCommand("select DATEPART(yyyy,orderdate) as y, DATEPART(mm,orderdate) as m, DATEPART(dd,orderdate) as d, bno from bill", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
date.Add(dr["y"].ToString() + "-" + dr["d"].ToString() + "-" + dr["m"].ToString());
no.Add(dr["bno"].ToString());
}
con.Close();
foreach (var a in date)
{
Console.WriteLine("Inserting: " + date[i] + " With " + no[i]);
SqlCommand cmd2 = new SqlCommand("update bill set orderdate = '" + date[i] + "' where bno = " + no[i], con);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
i++;
}
Console.WriteLine("Order date changing completed \n\n");
Thank you for sharing your precious time thanks friends

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