Hello I have got this query that I would like to return '0,00' insead of '0'
When I tried to write it like this:
string sqlcom = "SELECT (ISNULL(s_prijmy, 0,00)), * FROM zajezd WHERE akce >= '" + txt_od.Text + "'AND akce <='" + txt_do.Text + "' AND rocnik='" + klientClass.Rocnik() + "'";
It gives me following Exception:
System.InvalidCastException: Specified cast is not valid. at
System.Data.SqlClient.SqlBuffer.get_Decimal()
May I ask how can I fix it ?
Thanks in adavance.
Future use of this '0,00' should be following :
this.chart1.Series["Příjmy"].Points.AddXY(myreader.GetString(myreader.GetOrdinal("akce")), myreader.GetDecimal(34).ToString()); // the 34th column
Change , with . in your query.
ISNULL(s_prijmy, 0.00)
I would also note that
GetDecimal(34)
gets the 35th column as it is zero-based...
Use:
GetDecimal(33)
for the 34th column.
Check here
0,00 is not decimal. Try 0.00 to cast it into the decimal in your query. And don't forgot to put 0.00 in single quotes '' if s_prijmy is type of varchar.
Try this
string sqlcom = "SELECT (ISNULL(s_prijmy, '0.00')), * FROM zajezd WHERE akce >= '" + txt_od.Text + "'AND akce <='" + txt_do.Text + "' AND rocnik='" + klientClass.Rocnik() + "'";
And yes as I already said the please try to use parameterized query.
What datatype is s_prijmy? if it is string, and you want to return a string of '0.00' then do
ISNULL(s_prijmy, '0.00')
If it is numeric, and you want to return a number in format 0.00, then do
ISNULL(s_prijmy, cast(0 as decimal(3,2)))
if s_prijmy has a greater precision that 2, eg decimal(4,3), then you will get 0.000
Try this way:
string sqlcom = "SELECT cast(ISNULL(s_prijmy, 0) as decimal(8,2)), * FROM zajezd WHERE akce >= '" + txt_od.Text + "'AND akce <='" + txt_do.Text + "' AND rocnik='" + klientClass.Rocnik() + "'";
You can format the data when you display it.
select the data as it is
string sqlcom = "SELECT s_prijmy, .........
then
var value = myreader.GetString(myreader.GetOrdinal("s_prijmy"));
value = string.IsNullOrEmpty(value)?"0,00":value;
now you can use above value in Points.AddXY
You must correct your presentation at client side. Look at the public string ToString(string format). Also here and here.
Related
I'm using this sql code to insert data into a table
"INSERT INTO electric VALUES('" + date.Text + "', '" + h1.Text + "', '" + h2.Text + "', '" + h22.Text + "', '" + h3.Text + "', '" + h4.Text + "', '" + h5.Text + "', '" + h6.Text + "', '" + h7.Text + "', '" + h8.Text + "', '" + h9.Text + "', '" + h10.Text + "');"
Sometimes I leave some TextBoxes empty and they are all int. but it won't insert into the table.
the error
I set the column default into 0 but still wont insert.
default
please help me to solve this problem.
thanks
Try this :
using(SqlConnection connection = new SqlConnection(yourConnectionString))
{
String query = "INSERT INTO electric (h1, h2, h3, h4) VALUES (#h1, #h2, #h3, #h4)";
using(SqlCommand command = new SqlCommand(query, connection))
{
int h1Data = 0;
Int32.TryParse(h1TextBox.Text, out h1Data);
int h2Data = 0;
Int32.TryParse(h2TextBox.Text, out h2Data);
int h3Data = 0;
Int32.TryParse(h3TextBox.Text, out h3Data);
int h4Data = 0;
Int32.TryParse(h4TextBox.Text, out h4Data);
command.Parameters.AddWithValue("#h1", h1Data);
command.Parameters.AddWithValue("#h2", h2Data);
command.Parameters.AddWithValue("#h3", h3Data);
command.Parameters.AddWithValue("#h4", h4Data);
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
{
// Error
}
}
}
Explain :
The textBoxs should be ints as you said so if not the error occurs !
Now it is easy, we create int var and get textBox content into it .. by default the int var equal zero and we use tryParse if textBox content isn't number, the conversion wouldn't be completed but the int var still have the default value which is zero and will be inserted into database (the same occurs with empty textBox or empty string).
You may need to edit it to work exactly as you want,
I hope it helps you .. good luck !
You are trying to store empty string ('') to int field. Default value will be used only if you skip field from the list to insert.
In other word you need to cast values to integer when you concatenate a query. I am not familiar with C# but from brief search it probably can be done with Int32.TryParse
OK so I am using MVS 2015 to right a database using windows Forms and C#
This is what I coded
internal static decimal getExpenseSum(int parsedProjectID, string type)
{
decimal value = decimal.Zero;
string query = "SELECT sum(TotalReceiptAmount) " +
"FROM Expense WHERE ProjectID = " +
parsedProjectID + " AND Type = " + type;
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
value = Convert.ToDecimal(cmd.ExecuteScalar());
conn.Close();
return value;
}
And I am getting a exception stating that the column name 'Parts' is not a valid column name. when "Parts" is the type string sent to the function.
type is varchar/string type, surround it with quotes:
string query = "SELECT sum(TotalReceiptAmount) " +
"FROM Expense WHERE ProjectID = " +
parsedProjectID + " AND Type = '" + type + "'";
^____________^
For better readability do this for your varchar/string types:
type = "'" + type + "'";
string query = "SELECT sum(TotalReceiptAmount) " +
"FROM Expense WHERE ProjectID = " +
parsedProjectID + " AND Type = " + type ;
It seems like the string that you send to function - 'Parts' should be in quotes when you compare for e.g. the resulting query from your code should be :
SELECT sum(TotalReceiptAmount) FROM Expense WHERE ProjectID = parsedProjectID AND Type = 'Parts';
You need to quote your type parameter, otherwise it will be interpreted as a column name instead of a value:
string query = "SELECT SUM(TotalReceiptAmount) " +
"FROM Expense WHERE ProjectID = " +
parsedProjectID + " AND Type = '" + type + "'";
^ ^
Better yet is to use prepared statements to
handle parameter types automatically;
safeguard your code against sql injections;
optimize query execution.
New error Object cannot be cast from DBNull to other types.
using
internal static decimal getExpenseSum(int parsedProjectID, string type)
{
decimal value = decimal.Zero;
type = "'" + type + "'";
string query = "SELECT sum(TotalReceiptAmount) " +
"FROM Expense WHERE ProjectID = " +
parsedProjectID + " AND Type = " + type;
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
value = Convert.ToDecimal(cmd.ExecuteScalar());
conn.Close();
return value;
}
OK so that worked but I am doing it three times for ""Parts"" ""Tools"" and """other"" and of course Ive just only entered one for parts and then the form goes back to the project form and tries to do theese sums and there is nulls for Tools and Other. so Ill have to do a try catch.....
but thank you all for the solve....
That is the meat of my project if you will workflow add customer....
Now on to adding projects to existing customers and then reports. YEAH and once again thank you
I am executing a MS Access Query through c#. Below is the query
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours" +
"' WHERE EMPID = '" + Eno +
"'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") +
"# FROM INOUTPunching";
which is giving below error
{"The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect."}
I need to know:
Why is this not working?
Is there any simplier method?
You should place the FROM clause before the WHERE clause. That is the problem with your query. And you have an extra single quote which should be removed. This is the query you should write:
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM INOUTPunching " +
" WHERE EMPID = '" + Eno +
"'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";
And about a simpler method: no, this is the simplest method but it is prone to SQL injection attacks. Replace it with a parameterized query (assuming you have an OldDbCommand name cmd):
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM INOUTPunching " +
" WHERE EMPID = #EmpId AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";
cmd.CommandType = CommandType.Text;
cmd.CommandText = SelWHQuery;
cmd.Parameters.AddWithValue("#EmpId", Eno);
I am having a problem inserting a record, the error says, "Error converting data type varchar to numeric."
This is my set of codes:
private void btnSearchCustomer_Click(object sender, EventArgs e)
{
//Get Customer Records
DataSet dsCustomer = new DataSet();
dsCustomer = GetRecords("Customers");
frmBasicSearch newSearch = new frmBasicSearch();
newSearch.myDataSet = dsCustomer;
newSearch.ShowDialog();
int myRowPosition = newSearch.myRowPosition;
if (myRowPosition != -1) //will display the value inside the textboxes
{
//concuntinated values
this.txtCustomerNo.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerNo"].ToString();
this.txtCustomerName.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerName"].ToString();
this.txtCustomerAddress.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerAddress"].ToString();
groupProduct(true); //this will activate the buttons from the Product Section
}
cn.Close();
cn.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = cn;
cmdInsert.Transaction = trnOrder;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText =
"INSERT INTO ShoppingCart " +
"(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentNo, AgentName, InvoiceNo, TotalAmount, OrderStatus) " +
"VALUES ('" +
dtpOrderDate.Value.Date.ToString() + "', '" +
txtCustomerNo.Text + "', '" +
txtCustomerName.Text + "', '" +
txtCustomerAddress.Text + "', '" +
txtPONo.Text + "', '0', 'Agent', '" +
txtInvoiceNo.Text + "', '" +
lblTotal.Text + "', 'Void'); " +
"SELECT TOP 1 ShoppingCartNo FROM ShoppingCart " +
"ORDER BY ShoppingCartNo DESC;";
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
txtOrderNo.Text = nShoppingCart.ToString();
cmdInsert.ExecuteNonQuery();
cn.Close();
}
the highlighted part is the
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
I cannot seem to know where is the problem? thank you for your help.
I think you have taken "CustomerNo" field in database numeric field and you are trying to insert varchar or string value in that field as i am able to see your code in which you are putting "txtCustomerNo.Text" which will contain string value. You should convert your value fisrt in int or whatever you have taken your database field.
Hopefully this will be helpful for you.
Can you run the script without the Convert method. Replace it with:
string nShoppingCart = cmdInsert.ExecuteScalar().ToString();
Then see what nShoppingCart value is, and see if that would ever convert to an integer.
Try adding following part
Convert.ToInt16(lblTotal.Text)
Okay, so in the past few weeks I've probably written about 40 select statements. So, I know how to do it. And I've just written another one, but this time I need to use ComboBox values to match against, and it keeps resulting in the names of the column (the right column, mind you), instead of what's inside the column.
string st = "SELECT '" + txtchange.Text + "'
FROM mysql_9269_dbase." + pages.Text + "";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
cd.CommandType = CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while(msdr.Read())
{
txt.Text = msdr[0].ToString();
}
Now, why is it returning the column name instead of the content of that column?
Lose the single quotes.
Change
"SELECT '" + txtchange.Text + "' "
to
"SELECT " + txtchange.Text + " "
In sql you can do it like this.
string query = "Execute("+"'SELECT " + txtchange.Text + " FROM mysql_9269_dbase." + pages.Text + "')";