How to pick out specific parts of a text box? - c#

I am trying to pick out specific letters/numbers from a text box, because each means something. After that I am trying to display in a label what it means.
So if I have a number AB-123456, I need to first pick out AB something like:
If (textBox.Text.Substring(0,2) == "AB") {
//Display to a label
}
First off, this doesn't work and I also tried substring(0,1) but also was receiving errors when I used my clear button to clear the text box.
After that I still need to pull the rest of the numbers. The next one I need to pull and define is 123, then 4 by itself, 5 by itself, and six by itself.
How do I go about pulling each of these individually if substring isnt working?

Try this:
if (textBox.Text.StartsWith("AB"))
{
//Display to a label
}
Use this if you don't want to have to check the Length of the text first. Also, you can include a StringComparison argument if you want to ignore case.

string input = textBox.Text;
// check the length before substring
If (input.Length >= 2 && input.Substring(0,2) == "AB") {
//Display to a label
}
or use regex:
string txt="AB-1234562323";
string re="AB-(\\d+)"; // Integer Number 1
Regex r = new Regex(re,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)// match found
{
// get the number
String number=m.Groups[1].ToString();
}

Related

Check if 2 textboxes have the same data type

I am trying to make a Kinematics Calculator on C#, you input 3 numerical values, a letter and a question mark (each in different text boxes). The letters change depend on the value you are inputting. For example, you would input "A" for acceleration but "T" for time. Unfortunately, the problem is I need a function that finds if 2 letters are present in 2 different text boxes and display a message box saying you cannot do that, etc
For example,
If I had a textbox that had a user input of "A" and another textbox that had a user input of "T", then I need a message box that outputs "Only 1 letter allowed, please try again".
Is there a way to do this?
You could do a "tryParse" on each text field. If it fails you know there is a character present. You then count the amount of "fails". There are many different ways to detect how many alpha characters there are. You may need to strip the "?" field with .Replace("?","") too.
int parsedValue = 0;
int lettersPresent = 0;
if (!int.TryParse(textBox1.Text, out parsedValue)) lettersPresent++;
if(!int.TryParse(textBox2.Text, out parsedValue)) lettersPresent++;
if (lettersPresent > 1) MessageBox.Show("Only 1 letter allowed, please try again");
It may be easier to just combine the textbox values and check with contains as well:
string combined = textBox1.Text + textBox2.Text;
int letterCount = 0;
if (combined.Contains("T")) letterCount++;
if (combined.Contains("S")) letterCount++;
if (letterCount > 1) MessageBox.Show("Too many..");
I am assuming you are parsing the letters out at some point so it probably should just be included inside that method.
You can use Char.IsLetter() method alongside the LINQ Any()to achieve that. Char.IsLetter() method will return true if the provided char is an uppercase or lowercase letter. Note that if any of the chars of the string is a letter, the expression return will return true, if you need to check if all the characters of the string are a letter, use .All() instead of .Any()
string textbox1Value = "V";
string textbox2Value = "T";
bool hasTwoLetters = textbox1Value.Any(x => char.IsLetter(x)) && textbox2Value.Any(x => char.IsLetter(x));
if(hasTwoLetters)
{
// Display alert
}

Getting certain characters in a textbox

Let's say I wanted to create a simple calculator, and I have it set up so whenever you press one of the operation buttons (+,-,*,/), it sets whatever you have in the textbox as the first number and then add the operation to the textbox. Now if I wanted the second number to be set to whatever is after the operation (+,-,*, or /) when I press the solve button, how would I go about doing that?
You can use the string Split method to get your factors like this:
string calculation = "5+1";
string[] factors = calculation.Split('+');
//factors[0] == 5
//factors[1] == 1
To handle string splitting on multiple operands use:
string calculation = "4+8-2";
string[] factors = calculation.Split(new char[] {'+' , '-' });
//factors[0] == 4
//factors[1] == 8
//factors[2] == 2

How can I show a string until the given condition valid, but no longer (console app)

I'm making a console adventure game for practice and I need to display a text when my character close to an object (at adjacent position). This string must be displayed until the character close to the object, but if it step further the text need to gone.
I tried this:
if (field[ver, hor + 1] == '█')
{
notice_detection = "DETECTION: '█' (right)";
Console.SetCursorPosition(37, 0);
Console.Write(notice_detection);
}
else
{
if (notice_detection != null)
{
notice_detection = " ";
Console.SetCursorPosition(37, 0);
Console.Write(notice_detection);
}
}
It's working but not too elegant. I'm sure a better solution exist.
My first try was to put 'notice_detection.Remove(0)' into else, but its didn't remove the already displayed string (by the way, why it's happened?).
Thanks!
The .Remove() method on strings returns a new string containing the remaining characters that are not removed starting from the given index. Calling it with 0 means that it removes everything from index 0 and returns the remaining, an empty string. If you write an empty string to the console, that looks like it does not did anything.
You can also replace your whitespacing hard coded string with a dynamic sized one filled with whitespaces like this:
var clearChars = new string(' ', notice_detection.Length);
Console.SetCursorPosition(37, 0);
Console.Write(clearChars);

Verify empty field Selenium C#

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}

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

Categories

Resources