Calculation Between Datetimepicker and Textbox - c#

i have a datimepicker Date Recieve and Assumed Date of Arrival and a textbox of LeadTime
all i can see in the internet is a calculation between two datetimepicker , but i want to do is just like this
int date=0;
int lead_time = Int16.Parse(tb_leadtime.Text);
date = dt_recieve.Value - lead_time;
dt_arrival.Value = "MMM/" + date + "/yyyy";
any suggestion and opinion will be helpful.

I see a big problem in your code. Appending textbox.Text directly to an sql string is not safe. You are exposing your system for sql injection. I would recommend always use Stored Procedures with definite input parameters and errors. For your actual question could you please write a little more detail to understand the problem better? I may be abel to help you.

Related

Ways to handle different data type restrictions in a "textbox" that come from SQL Server - C# Winforms

I am currently developing a software to integrate and be a nice front end UI to a database that doesn't have a front end UI. Part of this UI has a spot where there is a listbox on the left and on the right will be multiple sections of a drop down box on the left and a "textbox" on the right with an "and" and "or" radio button below it. It looks similar to the following linked picture.
So with that being said, one of the things I want to do is based on the column that is chosen on the left, the "textbox" will restrict/force reformat the data entered accordingly. So if it is a column of datetime formatting, then the textbox will only allow that kind of input. If the restriction is int[x], then the only input will be no more than the limitation of the integer, etc. etc. but not allow any letters to be inputted.
So this is where the real struggle comes in. I am struggling to figure out how to only allow specific input to the box based on the column chosen. Do I leave it as a text box and then use conditional statements that restrict the data input based on the formatting of the column? (Which this is how I am planning on currently programming it. However, this requires a lot of conditions and making sure to try and handle any and all possibilities out there.) Or is there a better way to handle the different types of SQL Server data types that will potentially be present? As in I create a box with the appropriate input restrictions and somehow dynamically swap them in/out based on the column selected at the time.
The biggest one that makes me question is the datetime formatting. I would love to use a date picker box (make sure I make it as idiot proof as I can). However, I am not sure if there would be an easy way to switch between a date picker box and any other boxes that could be necessary to have and have it all be seamless.
NOTE: All of the data will be stored so that if you go back to a column you already input data for, it will pull it back up.
Grateful for all of the feedback and input.
The way I read your question, you have solved the issue of determining the datatype of the SQL Server column. If that is correct, then all you would need to do is swap out controls based on the datatype of the column. Something like the following:
switch (columnType)
{
case int:
TextBoxInt.Visible = true;
TextBoxString.Visisble = false;
DateTimePicker.Visible = false;
break;
case string:
TextBoxString.Visible = true;
TextBoxInt.Visible = false;
DateTimePicker.Visible = false;
break;
case DateTime:
DateTimePicker.Visible = true;
TextBoxInt.Visible = false;
TextBoxString.Visible = false;
break;
}
Then you can handle limiting the input for each of the controls appropriately based on the datatype that it is for.
Maybe what you're looking for is to possibly handle the datatypes by letting sql do the work for you.
Sometimes it seems there's no way out of validating the user input with conditionals, but there are ways of making it simpler.
For many of problems handling the conditions you can probably use different parsing methods that throw exceptions. When the exceptions is thrown you can have it control the bool condition for submit. DateTime.Parse() is one of them.
For the date-time parsing problem you may be experiencing maybe this post to convert the textbox to a string and use DateTime.Parse(). DateBox Forced Formatting Logic.
Additonally, rather than a text box it may be useful to use a DateTimePicker object.

How to format currency from database

The goal
I want to format correctly the currency from database.
The problem
I'm formatting the currency from database with this:
#String.Format("{0:C}", #Model["MinProductPrice"])
The problem is: 150 have to be 1,50, and not 150,00 — and this formatting is doing this.
What is the right formatting type to my case?
You probably want to divide the number by 100 first (remember to change the type), so 150 becomes 1.50, which gets converted to "1,50" depending on locale:
#String.Format("{0:C}", #Model["MinProductPrice"] / 100.0m)
I'll extend my comments into an answer, I think that's more appropriate. I think you should change the column type to a money or decimal type to prevent bugs by making the use of the column more obvious. Your output on your page will be correct and won't require any "magic numbers" to get it to print out properly.
Just a note but you can also print a currency string doing this:
#Model["MinProductPrice"].ToString("C")
I attributed the casting responsibility to database. I'm using MySQL and the query is like this:
ROUND(CAST(MIN(`map`.`Product_Price`) AS DECIMAL)/100,2) as `minProductPrice`
Anyway, I would to thanks jlafay and csharpler about their answers — they were very helpful and worked well for me.

Datetime format read from Excel file

I have a little funny problem that I would like to share with you and am thankfully expecting from you some replies because I don't have an answer myself.
I have a DataGridView (dgv) in which one column is saved for datetime display.
I initialize it like a date string often used in MySQL, i.e 2011/1/3 in the dgv construction, and sure enough it displays correctly as a human readable string, that is 1/3/2011. I then save all the displayed content into another excel file.
After that I try to reopen it, here is the code after pressing the Open button
private void OpenClicked(object sender, ....)
{
dataGV.Rows.Clear();
OpenAndBindXls(filename,dataGV);
}
Sadly, the datetime display is not as expected, it is all 5762,3552,3354 etc.
I have two real questions,
[1] How can I explain the above problem ?
[2] In the above code, it only deletes rows, what methods should I use if I would like to delete even the columns but still keep the instance alive?
[Edit] Sorry the second question was made when my mind wasn't fresh at all, I noticed my stupidity. I correct it by just add dataGV.Columns.Clear(); :-D. How stupid! Well I am tired, I will take some sleep to refresh my mind now. Thanks anyway for reading.
I think that you are getting the date time format in ticks and not as you expect.
You can try either converting the data before binding or use the CellFormatting event to convert the value to a visual datetime:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx

TimeSpan field types in Crystal Reports or Active Reports

In a report, I have to implement timespan fields (For example duration of an activity). At the end of the report, a summary based on it should be included.
Neither Crystal Reports nor Active Reports support TimeSpan fields. I don't want to use any formula or other workarounds. Simply just show the TimeSpan fields (like 1:45, 45:23, 0:30) and show the summary at the end (like 109:20).
Any suggestion?
Try my ElapsedTime() function; use it with the summary field's Display String formula.
It is difficult to say for sure without knowing more information such as why you don't want to use formulas and whether this is a TimeSpan data type in SQL Server or it is stored in some other way in the database, or being calculating somehow (e.g. in application code), etc...
Without more information though, a formula is the right way to solve this in ActiveReports as well as Crystal Reports. Since you need a summary, in ActiveReports (where I have the most experience) I'd say the best way to do this is bring in the timespan value as a single numeric value as number of minutes. This will allow you to use the normal no-code ActiveReports summarization features as described here.
Then to format the number into the desired output text use a formula in the DataField property of the TextBox such as: =Math.Floor(Minutes/60) + ":" + (Minutes % 60). More information about using formulas in the DataField property is here and here.
Scott Willeke
GrapeCity

sql type float, real, decimal?

well in my database i had a colum for price of one product
i had it as float, my problem is if i saved it since my c# application
as 10.50 .. in a query it returns 10,50 and if i update i get a error
10,50 cant convert to float ... or something so..
and if i saved it as decimal, in queries inside sql management .. are ok..
but in my c# application... i get the same error..
10.50 retuns as 10,50 i dont know why, and how to solved it.. my unique solution is saved it
as varchar...
That's a localisation problem of some sort. 10,50 is the "European" way of writing ten and a half. If you're getting that from your select statements then your database is probably configured incorrectly.
Generally speaking you should use the same type throughout your layers. So if the underlying types in the database are x, you should pass around those data with identical types in c#, too.
What type you choose depends on what you are storing--you shouldn't be switching around types just to get something to "work". To that end, storing numeric data in a non-numeric type (e.g. varchar) will come back to bite you very soon. It's good you've opened this question to fix that!
As others have miraculously inferred, you are likely running into a localization issue. This is a great example of why storing numbers as strings is a problem. If you properly accept user input in whatever culture/localization they want (or you want), and get it into a numeric-type variable, then the rest (talking to the DB) should be easy. More so, you should not do number formatting in the database if you can help it--that stuff is much better placed at the front end, closer to the users.
I think your setting in windows regional and language for decimal symbol is wrong.please set it to dot and again test it.
This may help out for temporary use but I wouldn't recommend it for permanent use:
Try making it so that just before you save the file, convert the number to a string, replace the commas with periods (From , to .) and then save it into the database as the string, hopefully it should see that it is in the correct format and turn it into what the database sees as "Decimal" or "Floating".
Hope this helps.
Yep, localization.
That said, I think your pice is being stored on a "money" field in SQLServer (I'm assuming it's SQLServer you're using). If that was a float in the DB, it would return it with a normal decimal point, and not the European money separator ",".
To fix:
Fist DO NO USE FLOAT in your c# code, unless you absolutely require a floating point number. Use the decimal type instead. That's not just in this case, but in all cases. Floating point numbers are binary (base-2), not decimal (base-10), so what you see in the interface is only a decimal approximation of the actual number. The result is that frequently (1 == 1) evaluates as false!
I've run into that problem myself, and it's maddening if you don't know that can happen. Always use decimal instead of float in c#.
Ok, after you've fixed that, then do this to get the right localization:
using System.Globalization;
...
NumberFormatInfo ni = new NumberFormatInfo();
ni.CurrencyDecimalSeparator = ",";
decimal price = decimal.Parse(dbPriceDataField, ni);
Note that "dbPriceDataField" must be a string, so you may have to do a ".ToString()" on that db resultset's field.
If you end up having to handle other "money" aspects of that money field, like currency symbols, check out: http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
If you need more robust error handling, either put that decimal.Parse in a try/catch, or use decimal.TryParse.
EDIT --
If you know what culture (really, country), the db is set to, you can do this instead:
using System.Globalization;
...
CultureInfo ci = new CultureInfo("fr-FR"); // fr-FR being "french France"
decimal price = decimal.Parse(dbprice, ci.NumberFormat);
Such problems were faced by me in my Web Apps... but i found the solution like I was fetching my price value in textbox. So I was have database attached with that. So when you attached your database with textbox... When you right click textbox and click Edit DataBinding.... in that you have to provide.... type like in Bind Property..... {0:N2}
This will work only for web apps or websites... not for desktop applications...

Categories