How to concatenate two values into text box in c#? - c#

I have two values, I want to cast these values into a text box. The way I tried is mentioned below
string time="00";
int Result ="02";
textresult.Text=result+' '+time;//first way error result
textresult.Text=(CAST(Result AS varchar(50))+' '+CAST(time AS varchar(50)))//second way..syntax error.
I need output as 02:00 format in text box. Please suggest a way to solve this????

Try this:-
string time = "00";
int Result = 02;
textresult.Text=Result.ToString("D2") + ":" + time;

Try below.
textresult.Text=string.Format("{0}:{1}",Result.ToString("D2"),time);
Your code reports syntax error because there is. It seems you are using C# like sql syntax!

This might help.
string time="00";
int Result =02;
textresult.Text = String.Format("{0}:{1}",Result.ToString("D2"),time);
Fiddle link

Related

Variable decimal formating in string interpolation

I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).
string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";
Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.
This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.
Any ideas ?
You can, but you have to use explicit ToString call like this:
string format = "D4";
string sequenceNumber =
$"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";

Formatting String With LEading Zero's

I am trying to convert an object (coming from a SQL server), into a integer so I can format the number to have the correct amount of zero's in front of it.
For example:
If I were to have 25.6, I would need it to be 0025.6.
Now I have looked online on how to do this, but the methods that I have seen people post are not working for me. I am not entirely sure why. I am trying to format GlobalVariables.grossweightafter. I read the value GlobalVariables.grossweight from the SQL server, but then when I TryParse it, it loses its value. The code I have is below:
while (TransferRecord.Read())
{
//Pulling data from the SQL server. getting data for every line of code as specified.
GlobalVariables.baledate = TransferRecord["keyprinter_datetime"];
GlobalVariables.baleline = TransferRecord["pulp_line_id"];
GlobalVariables.baleid = TransferRecord["bale_id"];
GlobalVariables.grossweight = TransferRecord["bale_gross_weight"];
GlobalVariables.grossweightflag = TransferRecord["gross_value_flag"];
GlobalVariables.baleairdrypercent = TransferRecord["bale_airdry_pct"];
GlobalVariables.airdryflag = TransferRecord["airdry_value_flag"];
//Converting the date, and the baleid to fit in the string.
DateTime.TryParse(GlobalVariables.baledate.ToString(), out GlobalVariables.baledateafter);
int.TryParse(GlobalVariables.baleid.ToString(), out GlobalVariables.baleidafter);
int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter);
GlobalVariables.grossweightafter.ToString("0000.0");
//Calling the WriteData method.
WriteData();
}
So I was wondering if anyone can catch what I am doing wrong, or they can help me out on the correct way to go about this.
What #Hans Passant was saying is that you need to assign the value returned from .ToString. That line should be:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
The last lines should be
if(int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter))
{
string grossWeightAfter = GlobalVariables.grossweightafter.ToString("0000.0");
//you need to save the string returned from the ToString-method somewhere or it will be lost.
///Alternatively, if GlobalVariables can contain strings aswell:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
}
else
{
//React on value not being an int
}
Maybe you should try to use double.TryParse() method instead of int.TryParse(), because int does not have fractional part?
Also, you need to store ToString() result to a string variable. Your code should be like this:
GlobalVariables.grossweightafterstring = GlobalVariables.grossweightafter.ToString("0000.0");

How to affect formatting of dynamically created label text in c#

I think this should be a pretty easy question to answer but I can't seem to figure it out.
I am adding text to labels from a sqldatasource in c#. All of that works, but I want to be able to format the text. I want to 1) be able to change the format to 0.00 (instead of a string of decimals) and I would also like to be able to add words before the text. I assume I need to somehow use the string.format command but can't figure out how to work it in. Any help would be greatly appreciated. Here's my code below:
DataView dvSql = (DataView)DeskSummary.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drvSql in dvSql)
{
Desk.Text = drvSql["Deskname"].ToString();
MarginLabel.Text = drvSql["margin"].ToString();
CurrentCI.Text = drvSql["comp_index_primarycomp"].ToString();
WalMartCurrentCI.Text = drvSql["comp_index_walmart"].ToString();
ForecastMargin.Text = drvSql["margin_forecast"].ToString();
WalMartForecastCI.Text = drvSql["comp_index_walmart_forecast"].ToString();
ForecastCI.Text = drvSql["comp_index_primarycomp_forecast"].ToString();
}
You can pass the format argument to the ToString() method like so:
MarginLabel.Text = drvSql["margin"].ToString("0.00");
However, as you said you wanted to prepend some text. Therefore, I recommend:
MarginLabel.Text = String.Format("Prepended text {0:0.00}", drvSql["margin"]);
Note: I just picked one of your labels; I'm not sure which ones get special formatting treatment.
use the
string.Format("This is a before text {"0"},your param)
// you can add as many variables and {""} string literals as you need just make sure that you separate the variables with a ","
Here is the code
string stringNumber = "5123.34214513";
decimal decimalNumber = Decimal.Parse(stringNumber);
string output = String.Format("Your text: {0:0.00}", decimalNumber);
Console.WriteLine(output); //Your text: 5123.34
This works if the column is of type string
String.Format() will do what you need for prepending/appending text values,
string.Format("prepend text {"0"} append text", paramString)
But if you want to actually format the value you are getting back from SQL, then you would need to use String.Format() on that value as well as possibly some RegEx expressions and/or .ToUpperCase or .ToLowercase for your capitalization... something like.
var capitalizedString = paramString.subStr(0,1).ToUppercase + paramString.subStr(1, paramstring.Length);
string.Format("Prepended text {"0"} plus appended text", capitalizedString);

C# Get Date From Computer

I'm trying to get the date into a string in C#. I want the format of:
2011.02.14
Which is, YYYY.MM.DD
Can someone please let me know the command for this? And also is there a way to do like Date(-1)?
Thanks.
System.DateTime.Now.ToString("yyyy.MM.dd");
System.DateTime.Now.AddDays(-1)
For the first:
string s = DateTime.Now.ToString("yyyy.MM.dd");
For the second, you'd need to be explicit about what Date(-1) should return, but I expect it involves var foo = someDate.Add(timespan); or var foo = someDate.Add{SomeInterval}(delta);
Declare a string like :
string mydate;
myDate = DateTime.Now.ToString("yyyy.MM.dd");
messagebox.show(myDate);
You can do that using DateTIMe's ToString method, more info on MSDN

C# - Given a string that is representing a numeric percentage, a way to extract the whole percentage? [duplicate]

I don't want to do any rounding, straight up, "39%".
So "9.99%" should become "9%".
I hope this will work.
string str = "39.999%";
string[] Output = str.Split('.');
Output[0] will have your Answer.
Thanks
string myPercentage = "48.8983%";
string newString = myPercentage.Replace("%","");
int newNumber = (int)Math.Truncate(Double.Parse(newString));
Console.WriteLine(newNumber + "%");
There maybe hundred ways of doing this and this is just one :)
Probably a Regex. I'm no master of regular expressions, I generally avoid them like the plague, but this seems to work.
string num = "39.988%";
string newNum = Regex.Replace(num, #"\.([0-9]+)%", "%");
One way to do it:
"39.999%".Split(new char[] { '.' })[0] + "%";
int.Parse("39.999%".Split('.')[0])
Doing this gives you a nice int that you can work with as you see fit. You can stick a % sign on the end with whatever string concatenation floats your boat.
Now we have two questions asking the same thing..
Heres my crack at it.
"39.9983%".Split('.')[0] + "%";
Console.WriteLine("{0}%", (int)39.9983);
I'm guessing you want a string returned? Probably the laziest way to do it:
string mynum = "39.999%"
mynum = mynum.substring(0, mynum.IndexOf('.'));
mynum += "%";
To get an int, you could cast the result of line 2.

Categories

Resources