Code returning false on equal compare? - c#

Problem I currently have:
My server returns data back to the client, this includes a name. Now I want the client to grab this name and compare it. However for the past 3 hours I am stuck at this problem and I dont want to cheap fix around it.
My server returns a value and then a name, ex: random23454#NAMEHERE
I split the value using:
string[] values = returndata.Split('#');
And then I am doing:
if (textBox3.Text == values[1]) {
MessageBox.Show("equal");
}
However, the problem here is. I cant get it to be equal, I tried other methods but it just dont display equal.
What I have done:
Print textBox3.Text to a textbox and print values[1] to a other textbox and compared with my eye and mouse (Using invoke due to threading).
Used the .Trim() function
Using the .ToString() on values[1] (Just for the hell of it)
Assigned them both to a complete new string, trimmed them and compared them
Dragged the comparing outside the thread using:
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
and perform the same check.
My code:
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
if (readData.Contains("#") && readData.Contains("random"))
{
string[] values = returndata.Split('#');
string name = values[1].Trim();
if (textBox3.Text == name)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
}
What else can I do? I just dont understand that it is not equal..
Thanks in advance.

The data you're getting back from the server could be an array of bytes. Try converting the response to a string first before splitting. Also try printing the response (or the response's type) to console to see what you get before going any further.
Also make sure the length of each string is the same. Maybe give utf-8 a try instead of ASCII? Like so:
System.Text.Encoding.UTF8.GetString(inStream);

string name = values[1].Trim();
I think you want values[2] here. The way I read the documentation for Split, the element at index 1 will be the (blank) separator indicator.

Related

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

Checking a checkbox based on a textbox value

The code I have here is supposed to load three separate values from three lines in a .txt file. This works fine so far. LOAD1 works well, and gets converted to an integer and then put back into the program as expected.The trouble is LOAD2.
What I'm trying to do: I want this bit of code to check whether the text "counter clockwise" is the text in LOAD2. If it is, I want it to automatically check a checkbox (RotDir, which is also available for manual input in the main program). The only other available text that can be in that textbox is "Clockwise", which should leave RotDir unchecked. So ticking a checkbox by using input from a textbox, is this possible?
I figured, this can be solved with a basic true/false kind of statement, since it is only two values. However, this does not seem to work. Does anyone have an idea how I could solve this?
StreamReader sr = new StreamReader("C:\\Users\\Gebruik\\Desktop\\Settings.txt");
string[] lines = sr.ReadToEnd().Split(new char[] { '\n' });
LOAD1.Text = lines[3];
LOAD2.Text = lines[7];
LOAD3.Text = lines[10];
int A = Int32.Parse(LOAD1.Text);
ServoSpd.Value = A;
label1.Text = LOAD1.Text;
if (LOAD2.Text == "Counter Clockwise")
{
ServoDir.Checked = true;
}
else
{
ServoDir.Checked = false;
}
ServoDir.Checked = LOAD2.Text.ToLower() == "counter clockwise"
This will set the Checked property of your CheckBox to true if lowercase trimmed Load2.Text is "counter clockwise", otherwise it will be false.
If you are using strings to set some values try to do lowercase/uppercase comparison and also trim the string so that whitespaces are removed from the start and end of string.
EDIT:
Forgot to mention that you should try replace the whole if statement with the above code.
EDIT:
If above code does not work, try to set the IsChecked property to true/false.

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}

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

Categories

Resources