Checking a checkbox based on a textbox value - c#

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.

Related

Change Particular line of Multiline textbox in C#

I am unable to Change the specific string of a multiline TextBox.
suppose first line of multiline textbox is "Hello" & second line is "Bye".But when i trying to change the value of second line like below.
textBox1.Lines[1] = "Good bye";
When I saw the result using Debug mode it was not "Good bye".
I also read this MSDN article & this stackoverflow question but can't get the desired answer.
As MSDN states (the link you provided):
By default, the collection of lines is a read-only copy of the lines in the TextBox.
To get a writable collection of lines, use code
similar to the following: textBox1.Lines = new string[] { "abcd" };
So, you have to "take" Lines collection, change it, and then return to TextBox. That can be achieved like this:
var lines = TextBox1.Lines;
lines[1] = "GoodBye";
TextBox1.Lines = lines;
Alternatively, you can replace text, like Wolle suggested
First you need assign textBox1.Lines array in variable
string[] lines = textBox1.Lines;
Change Array Value
lines[1] = "Good bye";
Reassign array to text box
textBox1.Lines=lines;
According to MSDN
By default, the collection of lines is a read-only copy of the lines
in the TextBox. To get a writable collection of lines need to assign
new string array
Working with TextBox lines via Lines property are extremely ineffective. Working with lines via Text property is a little better, but ineffective too.
Here the snippet, that allows you to replace one line inside TextBox without rewriting entire content:
public static bool ReplaceLine(TextBox box, int lineNumber, string text)
{
int first = box.GetFirstCharIndexFromLine(lineNumber);
if (first < 0)
return false;
int last = box.GetFirstCharIndexFromLine(lineNumber + 1);
box.Select(first,
last < 0 ? int.MaxValue : last - first - Environment.NewLine.Length);
box.SelectedText = text;
return true;
}
You could try to replace the text of second line like this:
var lines = textBox.Text.Split(new[] { '\r', '\n' }).Where(x => x.Length > 0);
textBox.Text = textBox.Text.Replace(lines.ElementAt(1), "Good bye");

Set specific line of multiline TextBox in c#

Hello I am new to C Sharp & Windows Forms. I am unable to set the specific string of a multiline TextBox. I have tried below things so far.
textBox1.Lines[1] = "welcome to stackOverflow";
The above code does not give a compile time error but when I saw the result using Debug mode it was not expected.
Then i was also reading this MSDN article but in this there is a new collection created by using stream[] constructor but still the same problem arises.
It should give compiler error because you are trying to assign a string to char here:
textBox1.Text[1] = "welcome to stackOverflow";
Text property is of type string, when you use indexer on a string it gives you the char at that position. And also string is immutable so you can't really change a character at specific position without creating a new string.
You should set the Text directly like this:
textBox1.Text = "welcome to stackOverflow";
Or if you have more than one line in an array of string you should set the Lines property:
var lines = new [] { "foo", "bar" };
textBox1.Lines = lines;
Any value that you set directly to textBox1.Lines will be effected to textBox1.
There is a solution to resolve your problem. I think it's best way.
You have to clone the current value of your textbox. Then you set new value on it. Finally, you set back to textbox.
var curValue = (string[])textBox1.Lines.Clone();
curValue[1] = "welcome to stackOverflow";
//Set back to textBox1
textBox1.Lines = curValue;

How to pick out specific parts of a text box?

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

Code returning false on equal compare?

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.

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