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);
Related
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
Console.WriteLine("This field can not be empty");
}
Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?
Thank you in advance!
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.
For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.
This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.
For Empty / White space / Null, use following APIs of the string class
string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)
For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits
string pattern = #"^\d{20}$";
var booleanResult = Regex.Match(value,pattern).Success
I'm not sure that this way will work in your case. Code:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text or firstName.getAttribute("value");. When u will have this you will able to check
:
var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}
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");
I'm using a MaskedTextBox, with the following short date Mask: "00/00/0000".
My problem is that I wanna know when the control is empty:
if (string.IsNullOrEmpty(maskedTextBox1.Text))
{
DataTable dt = function.ViewOrders(Functions.GetEid);
dataGridView2.DataSource = dt;
}
It's not working, when maskedTextBox1 looks empty (and I'm sure it is), the if statement doesn't detect that it is null or Empty.
You can simply use:
maskedTextBox1.MaskCompleted
Or
maskedTextBox1.MaskFull
properties to check if user has entered the complete mask input or not.
I know this is old but I would first remove the mask and then check the text like a normal textbox.
maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
//...Perform normal textbox validation
I just faced this problem. I Needed the Masked Value, but also needed send empty string if the user didn't introduced any data in one single step.
I discovered the property
MaskedTextProvider.ToDisplayString so I use the MaskedTextbox with:
maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
BUT I always read the text from:
maskedTextBox.MaskedTextProvider.ToDisplayString()
This way, if the user has not introduced text in the control Text property will be empty:
maskedTextBox.Text == string.Empty
And when you detect the string is not empty you can use the full text including literals for example:
DoSomething((maskedTextBox.Text == string.Empty) ? maskedTextBox.Text: maskedTextBox.MaskedTextProvider.ToDisplayString());
or
DoSomething((maskedTextBox.Text == string.Empty) ? string.Empty: maskedTextBox.MaskedTextProvider.ToDisplayString());
If you set the property maskedTextBox.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals then the TypeValidationCompleted event validation will not work. To test if the short date maskedtextbox is empty you could just use:
if (maskedTextBox1.Text == " / /")
{
...;
}
Did you try trim.
if(string.IsNullOrEmpty(maskedTextBox.Text.Trim())
What logic are you trying to accomplish with the if statement? As it is right know, you are saying:
If the textbox is empty, set source of datagridview2 + to ViewOrder data. I'm not sure what your trying to do but I think you want the info to load if you have a date. to fix this all you have to do is add ! in the if statement which would make the if statement mean, if there is text in textbox then run code.
if( !(string.IsNullOrEmpty(maskedTextBox2.Text)))
In case of Telerik masked textbox which does not have MaskCompleted or MaskFull, a tricky solution would be this:
the mask always contain a charachter like this: "_" we check masked text box by this:
if (textbox1.Text.Contains("_"))
{
MessageBox.Show("Please enter the correct numbers!","Error",MessageBoxButtons.OK,MessageBoxIcon.Stop);
return;
}
if the text box is full, then it does not contain "_".
I believe the MaskedTextBox, (MTB), using the mask “00/00/0000” is an incorrect string to use for testing its emptiness. This is because the MTB is not like a normal textbox, and the short date mask must be used to determine its string value.
Let’s assume you have a MTB name mskDateOfBirth on your form. In order to test its emptiness, a statement like the following is needed
if (mskDateOfBirth.MaskedTextProvider.ToDisplayString() == "__/__/____")
{
// Do something when true
}
else
{
// Do something when false
}
I have tested this out using Visual Studio 2019 and it works fine. Hope this is helpful.
If the empty value is " / /", declare a constant for it:
const string EmptyDateInput = " / /";
And then later you can repeatedly use it to compare:
if (maskedTextBox1.Text == EmptyDateInput)
{
}
I test this concept and was success in in the following syntax
if( maskedtextbox_name.MaskkedTextProvider.ToDisplayString() == "__-__-____")
{
// Your function;
}
I currently output a currency value left-aligned, using the following:
String.Format(CultureInfo.CurrentCulture, "{0:#,##0}", value);
I wish to modify the string formatter so that I can right align this. Im not sure how to do it without affecting my existing formatter.
Could someone please advise?
EDIT: I Know it involves something similar to:
http://www.csharp-examples.net/align-string-with-spaces/
String.Format("{0,20:#,##0}", value); will do it.
Example.
not very clear what you actually mean, but I suppose, you are talking about
String.PadLeft method.
Example: to "align" right, you can:
string hello ="hello";
int supportedSymbCount = 10;
int padcount = supportedSymbCount - hello.Length;
if(padCount>0)
hello = hello.PadLeft(padCount);
This will add "pads" in front of the string as much as need to compose a string as long as 10 characters. Choose parameters more sutable to you, and it should work in your case.
For console output use the tab character as a separator,
Console.WriteLine( "\t{0:#,##0}", value )
For web use div class="numeric" with text-align="right".
For other outputs there are no generic solutions.
Use PadLeft or PadRight
int iTotalLength = 20; // Total length of string
char cPadChar = '0'; // Padding character
String.Format(CultureInfo.CurrentCulture, "{0:#,##0}", value).PadLeft(iTotalLength,
cPadChar);
txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
i want to find the last index of "," in my text and then remove that , but it is not working. Any Idea? txtBeautified is a richtextbox.
Are you retrieving the result of the operation?
value = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
If you are changing the value of the text box, you need to assign the result back to the text box:
txtBeautified.Text = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
Explanation: Strings cannot be changed. Functions that operate on strings do not change the strings, but return new strings. Therefore, the Remove function returns a string representing the result. To make use of this string, you will need to assign it to a variable/property or pass it into another function call.
Remove is a function. call should be:
txtBeautified.Text = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
Keep in mind that a string is immutable, so the Remove function returns you a new string. You'd need to reassign that new string back to the text box, like:
txtBeautified.Text = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1);