How do i get value from string textBox in C# - c#

I am newbee here right now, i'm trying to solve my problem code but it's doesn't clear.
I want to get value from my string textBox.Text. initial textBox is hmI7Segment1.Text. it's has string Format as Channel1.DV1.DB1.Level1. i wish to convert double value from this string into textBoxTarget.Text.
so, here is code problem:
hmI7Segment1.Text = "Channel1.DV1.DB1.Level1";
TextBox txtBoxTarget = converted.Format [hmI7Segment1.Text] as TextBox;
if all of you have solution, please help me to solve my case. thanks for all of you are.
Marbun

So if I understand correctly you wish to convert a value of a textbox which is a string, to a double right?
In that case you can do something like this:
Var stringInput = textbox.Text;
If(double.TryParse(stringInput, out var doubleInput))
{
//Do something with the double value
}
Else
{
//Input is not a valid double value, handle it by showing an error or something
}
Also you didn't specify the technology of your UI, is it forms or wpf?
Hope this helps

Related

how to set currency value for textbox in c# Windows form

During run time I want to insert some integer value on textbox it should be display like currency format
example : 1000000 is input
Expect 1,000,000.00
The below code is execute failure format
example 12345678
but actually i got 85,671,234 after first four(1234)integer the cursor automatically moved to backside
The code is
txtpurchasecost.Text = string.Format("{0:#,###,###.##}", double.Parse(txtpurchasecost.Text));
Thanks in Advance
txtpurchasecost.Text = string.Format("{0:N2}", double.Parse(txtpurchasecost.Text));
and you may also specify the culture manually for the separators:
txtpurchasecost.Text = string.Format(
CultureInfo.CreateSpecificCulture("en-US"),
"{0:N2}",
double.Parse(txtpurchasecost.Text));
Also you can check this article: Standard Numeric Format Strings
int temp = 0;
if (int.TryParse(txtpurchasecost.Text, out temp))
{
txtpurchasecost.Text = (int.Parse(txtpurchasecost.Text)).ToString("C2");
}
try this, this will fix your issue.

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 check if a MaskedTextBox is empty from a user input?

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;
}

How to convert innertext?

Hello I retrieve data from webbrowser control by use getelementbyid.
var element = webbrowser.document.getelementbyid(something);
i have a problem is cant convert to double which can convert to string.
i want to know about convertion to be double. it's can possible?
i tried already but ...
Input string was not in a correct format.
What's wrong?
Use value of html element.
Try this,
double d = double.Parse(webbrowser.document.getelementbyid(something).value);
I assume you're trying to do something like this;
string innerHtml = webbrowser.Document.GetElementById(something).InnerHtml;
double value;
if(Double.TryParse(innerHtml, out value))
{
// value is now populated
};
You could use
double d;
string element = webbrowser.document.getelementbyid(something).Value;
if (Double.TryParse(element, out d))
{
// Conversion succesful: in d you find your number
}
Take a look at Double.TryParse syntax.
After retrieving the value in string form, you should use Double.TryParse to parse it as a double, e.g.:
double number;
if (Double.TryParse(webbrowser.document.getelementbyid(something), out number))
{
// ... do something useful with 'number' ...
}

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

Categories

Resources