C# Textbox textresult wouldn't show up - c#

This is the code used to check whether the first number is greater than the second, but it is not working as expected. Can anyone please suggest the reason and correct me?
if (txtFirst.Text == "")
{
txtFirst.Text = "0";
if (txtSecond.Text == "")
{
txtSecond.Text = "0";
int first = Convert.ToInt32(txtFirst.Text);
int second = Convert.ToInt32(txtSecond.Text);
if (first < second)
{
txtResult.Text = "TRUE";
}
else
{
txtResult.Text = "FALSE";
}
}
}

Your scenario is working only if both the textboxes are blank(""). so it will be much better if you do like the following:
if (txtFirst.Text == "") {txtFirst.Text = "0";}
if (txtSecond.Text == ""){txtSecond.Text = "0";}
// it is good to check for null in this scenario since
// Convert.ToInt32() is not capable of handling null
int first = Convert.ToInt32(txtFirst.Text);
int second = Convert.ToInt32(txtSecond.Text);
if (first < second){txtResult.Text = "TRUE";}
else{txtResult.Text = "FALSE";}

Related

Writing a program in C# where depending on the Id (txtBxNumber) it will either update or create a new record in a text file and a Rich Text Box

fileName = txtBxFileNamePath.Text;
if (File.Exists(fileName))
{
if (txtBxDate.Text != null && txtBxNumber.Text != null && txtBxUnit.Text != null && txtBxUnitPrice.Text != null && txtBxShipTo.Text != null
&& txtBxOrdered.Text != null && richTxBxDesc.Text != null)
{
try
{
int higherThanZero = Int32.Parse(txtBxNumber.Text);
if (higherThanZero > 0)
{
using (StreamReader reader = File.OpenText(fileName))
{
string[] lines = File.ReadAllLines(fileName);
for (int i = 0; i < lines.Length - 1; i++)
{
string firstNum = lines[i].Substring(0, 2);
if (firstNum == txtBxNumber.Text)
{
string record = "hello ";
lines[i].Replace(lines[i], record);
}
else
{
int orderNum = Int32.Parse(txtBxOrdered.Text);
int unitPriceNum = Int32.Parse(txtBxUnitPrice.Text);
double tax = .13;
int taxInt = (int)tax;
int amount = orderNum * unitPriceNum;
string amountStr = amount.ToString();
int amountTotal = amount * taxInt;
string amountTotalStr = amountTotal.ToString();
amountList.Add(amountStr);
amountTotalList.Add(amountTotalStr);
string record = amountTotalStr.PadRight(30) + amountStr.PadRight(30);
richTxtBxRecord.Text += record + "\n";
using (StreamWriter write = new StreamWriter(fileName, true))
{
write.WriteLine(record + "\n");
write.Close();
}
}
}
}
}
else
{
richTxtBxError.Text += "Textbox Number must contain a digit higher than 0 ";
}
}
catch
{
richTxtBxError.Text += "Please make sure number text box is a digit";
}
}
else
{
richTxtBxError.Text += "please make sure that no text boxes are empty";
}
}
else
{
richTxtBxError.Text += "Please select a file that already exists";
}
I am having an issue where once i get past the try-catch statement "please make sure number is a digit, no code executes. I am trying to obtain the first few characters in a text file and match it with the users input. If the input is the same as what is already inserted in the text file, i update the whole record. If there is no match (non existent number) i write in a brand new record.
I can't quite follow your logic, but I tried. You should be able to take this code and do what you want (whatever it is).
I started by declaring some class level variables.
private DateTime _dateValue;
private int _numberValue;
private decimal _unitPrice;
private int _numberOrdered;
Then, since you have so many preconditions and so many text boxes, I factored out the validation and setting of these variables. It makes the logic (whatever it supposed to be) much easier to follow:
private bool ValidateUserEntry()
{
bool isError = false;
if (!File.Exists(txtBxFileNamePath.Text))
{
AddError("File Name must exist");
isError = true;
}
if (txtBxDate.Text == string.Empty || !DateTime.TryParse(txtBxDate.Text, out var _dateValue))
{
AddError("The date must be a valid date");
isError = true;
}
if (txtBxNumber.Text == string.Empty || !int.TryParse(txtBxNumber.Text, out _numberValue) ||
_numberValue <= 0)
{
AddError("You must enter a number greater than 0 for [Number]");
isError = true;
}
if (txtBxUnitPrice.Text == string.Empty || !decimal.TryParse(txtBxUnitPrice.Text, out _unitPrice) ||
_unitPrice <= 0.0m)
{
AddError("The unit price must be a positive decimal number");
isError = true;
}
if (txtBxShipTo.Text == string.Empty)
{
AddError("A ship to address is required");
isError = true;
}
if (txtBxOrdered.Text == string.Empty || !int.TryParse(txtBxOrdered.Text, out _numberOrdered) ||
_numberOrdered <= 0)
{
AddError("The Number ordered must be a number greater than 0");
isError = true;
}
if (richTxBxDesc.Text == string.Empty)
{
AddError("A description is required");
isError = true;
}
return !isError;
}
I also added two utility functions for managing the error list:
private void ClearError()
{
richTxtBxError.Text = string.Empty;
}
private void AddError(string errorMessage)
{
richTxtBxError.Text += (errorMessage + Environment.NewLine);
richTxtBxError.SelectionStart = richTxtBxError.Text.Length;
richTxtBxError.SelectionLength = 0;
}
Now comes the real code. Near as I can tell, you want to scan a text file. If the number in the first few character positions matches a number in your input, then you change the line to some constant text. Otherwise, you want to do a calculation and put the results of the calculation on the line of text.
My input file looks like this:
1 First
2 Second
3 Third
12 Twelth
13 Thirteenth
34 Thirty-fourth
and the code that I run looks like what's below. The logic makes no sense, but it was what I could discern from your code. Instead of trying to do things on the fly to a file (which never really turns out well unless you are really careful), I gather the output into a List<string>. Once I have all the output, I put it in a text box control and overwrite the file.
ClearError();
//check pre-conditions
if (!ValidateUserEntry())
{
return;
}
string[] lines;
using (StreamReader reader = File.OpenText(txtBxFileNamePath.Text))
{
lines = File.ReadAllLines(txtBxFileNamePath.Text);
}
List<string> newLines = new List<string>();
for (var lineIndex = 0; lineIndex < lines.Length; ++lineIndex)
{
var line = lines[lineIndex];
if (line.Length > 2 && int.TryParse(line.Substring(0, 2), out var linePrefixNumber) &&
linePrefixNumber == _numberValue)
{
newLines.Add("Bingo, hit the right record");
}
else
{
decimal tax = .13m;
var amount = _numberOrdered * _unitPrice;
var amountTotal = amount * (1m + tax);
//amountList.Add(amount.TosString());
//amountTotalList.Add(amountTotal.ToString());
var newRecord = $"{amountTotal,30:C}{amount,30:C}";
newLines.Add(newRecord); //every record but one will be the same, but, such is life
}
}
//at this point, the newLines list has what I want
//put it in the text box
richTxtBxRecord.Text = string.Join(Environment.NewLine, newLines);
//and write it out
using (StreamWriter write = new StreamWriter(txtBxFileNamePath.Text, append:false))
{
write.Write(richTxtBxRecord.Text);
write.Flush();
}
With inputs that look like:
Number: 12
Number Ordered: 3
Unit Price: 1.23
The output (oddly enough - but it's what I could figure from your code) looks like:
$4.17 $3.69
$4.17 $3.69
$4.17 $3.69
Bingo, hit the right record
$4.17 $3.69
$4.17 $3.69
You can see that the input line that had the 12 at the start gets switched for bingo. The rest get the same information. I'm sure that's not what you want. But, with this code, you should be able to get something that you'd like.
Also note that I treat all the currency values as decimal (not int or double). For the life of me, I have no idea what you were trying to do with the taxInt variable (it will always be zero the way you have coded it). Instead, I did a rational tax calculation.
All of the code below the catch block is inside an else block, so I wouldn't expect it to execute. If you want something to execute after the catch, remove it from the else block.

How do I accept a null line?

So I have a line of code that sometimes does not exist.
HtmlElement Pend = webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite");
Here is the rest of my code
string PendT;
webBrowser1.Document.GetElementById("ctl00_cphRoblox_JoinGroup").InvokeMember("click");
HtmlElement Pend = webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite");
PendT = Pend.InnerText;
Debug.WriteLine(PendT);
if (PendT == "Join Pending")
{
Debug.WriteLine("Join Pending");
Value = 1;
}
Now what I need help with is sometimes Pend is null and when I go to do PendT = Pend.InnerText; I get System.NullReferenceException. And that's probably because it cannot find Pend. Is there I way I can assign Pend a string value if it's null? I have tried
if (webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite").InnerText != null)
{
Debug.WriteLine("Join Pending");
Value = 1;
}
Although that hasn't worked.
You could check if Pend is null after you retrieve it. Do what you want with taht if check.
string PendT;
webBrowser1.Document.GetElementById("ctl00_cphRoblox_JoinGroup").InvokeMember("click");
HtmlElement Pend = webBrowser1.Document.GetElementById("ctl00_cphRoblox_AlreadyRequestedInvite");
if(Pend != null)
{
PendT = Pend.InnerText;
Debug.WriteLine(PendT);
if (PendT == "Join Pending")
{
Debug.WriteLine("Join Pending");
Value = 1;
}
}
else
{
// do something here
}

Why string type is not converting to int type?

I want to add two numbers. I am getting values from button in my textbox. I also succeeded in splitting string into substrings and store values of these substrings in variables. But i am not able to convert string type to integer type. That results in concatenation not in addtion.
Note :
I am using MVC to perform this task. And in model value1 and value2 is string type in model
Here is my code snippet:
if (button == "1"){
if (model.textBox == "" || model.textBox == null || model.textBox.ToLower().Contains("please enter value")){
model.textBox = "1";
} else {
model.textBox += "1";
}
}
if (button == "2") {
if (model.textBox == "" && model.textBox == null) {
model.textBox = "2";
} else {
model.textBox += "2";
}
if (button == "+") {
if (model.textBox == "" && model.textBox == null){
model.errormsg = "Please enter a number ";
} else {
model.textBox += "+";
}
if (button == "=") {
if (model.textBox.Contains("+")) {
model.value1 = (model.textBox.Split('+'))[0];
int value1 = int.Parse(model.value1);
model.value2 = (model.textBox.Split('+'))[1];
int value2 = int.Parse(model.value2);
model.textBox = model.value1 + model.value2;
}
return View(model);
If i got you correctly all you need to do is:
model.textBox = (value1 + value2).ToString();
model.textBox is of type string, so, when you do model.textBox += "1"; the only possible operation is concatenation.
To add them as integers you first need to convert your textBox to int.
Something like the following will work:
model.textBox = (int.Parse(model.textBox) + 1).ToString();
Try using int.Parse(textBox.Text).
It will crash if there is a non-numeric character in the string, but that's nothing a try-catch block won't fix.
Hope this helps!
if (button == "=") {
if (model.textBox.Contains("+")) {
model.value1 = (model.textBox.Split('+'))[0];
int value1 = int.Parse(model.value1);
model.value2 = (model.textBox.Split('+'))[1];
int value2 = int.Parse(model.value2);
model.textBox = model.value1 + model.value2;
}
Replace above code snippet with below code snippet:
if (button == "=")
{
if (model.textBox.Contains("+"))
{
model.value1 = (model.textBox.Split('+'))[0];
model.value2 = (model.textBox.Split('+'))[1];
model.textBox1 = (int.Parse(model.value1) + int.Parse(model.value2)).ToString();
}

How to assign data to an int if I checked radio button

I want to assign a data to an int volunteerEducation if I Checked radio button to save it to the database!
int volunteerEducation;
switch (volunteerEducation)
case radioButton9.Checked:
volunteerEducation= 9;
break;
case radioButton10.Checked:
volunteerEducation = 10;
break;
try this...
foreach(Control c in this.Controls)
{
if(c is RadioButton)
{
RadioButton rbtn = (RadioButton)c;
// now here you can use if else statements or Switch Statement
}
}
switch allows you to check for one of several values on a single variable. if statements allow arbitrary conditions, which can check a single variable or many. Hence, switch is unsuited for what you are trying to do.
There are a few obvious options:
Use a series of if ... else if statements
Use some fancier construct such as a lookup dictionary mapping to methods (Dictionary<RadioButton,Func<>> might be a good place to start), though if you are unfamiliar with such constructs as switch I'd strongly recommend against that (it's the old "you have to learn to walk before you start to run")
Iterate over the radio buttons and do your magic inside a loop
Such a loop would look like:
foreach (Control c in this.Controls)
{
RadioButton rbtn = c as RadioButton;
if(rbtn != null)
{
// ... your code to work with 'rbtn' goes here ...
if (rbtn.Checked)
{
// ...
}
}
}
Using as rather than is followed by an explicit cast is idiomatic, and also saves you a cast; null checking is almost certainly faster, and certainly not slower, than casting. The as operator gives you null if the given value cannot be cast to the given type. In the case where the value of the variable you are working can be changed from another thread (not likely in this case, but possible in other cases), it also saves you the headache of a nigh-impossible-to-reproduce bug when something changes the value of the variable out under your feet.
A set of if statements to do the same thing would be along the lines of
if (radioButton9.Checked)
{
// do something
}
else if (radioButton10.Checked)
{
// do something
}
Using else if mimics the behavior of a switch ... case ... break construct. If they are independent, simply omit the else. (Then, I'd suggest adding a blank line between the end of the if statement-block and the next if statement, for readability.)
I found the Answer and it's not really different from thus answers.
the Point is to declare int. e.g int volunteerEducation = 0; then you have to use if ... else if.
private void updateButton_Click(object sender, EventArgs e)
{
try
{
string volunteerID = updtIDTextBox.Text;
string volunteerName = updtNameTextBox.Text;
string volunteerZone = updtZoneTextBox.Text;
string volunteerStreet = updtStreetTextBox.Text;
int volunteerSex = updtMaleRadioButton.Checked ? 0 : 1;
DateTime volunteerBirthday = updtBirthdayDateTimePicker.Value;
if (updtHomePhoneTextBox.Text == "")
updtHomePhoneTextBox.Text = "0";
int volunteerHomePhone = int.Parse(updtHomePhoneTextBox.Text);
if (updtWorkPhoneTextBox.Text == "")
updtWorkPhoneTextBox.Text = "0";
int volunteerWorkPhone = int.Parse(updtWorkPhoneTextBox.Text);
if (updtMobile1TextBox.Text == "")
updtMobile1TextBox.Text = "0";
int volunteerMobile1 = int.Parse(updtMobile1TextBox.Text);
if (updtMobile2TextBox.Text == "")
updtMobile2TextBox.Text = "0";
int volunteerMobile2 = int.Parse(updtMobile2TextBox.Text);
string volunteerEmail = updtEmailTextBox.Text;
string volunteerJob = updtJobTextBox.Text;
string volunteerAffiliation = updtAffiliationTextBox.Text;
//The solution start from here
int volunteerEducation = 0;
if (radioButton10.Checked)
volunteerEducation = 1;
else if (radioButton11.Checked)
volunteerEducation = 2;
else if (radioButton12.Checked)
volunteerEducation = 3;
else if (radioButton14.Checked)
volunteerEducation = 5;
else if (radioButton15.Checked)
volunteerEducation = 6;
else if (radioButton16.Checked)
volunteerEducation = 7;
else if (radioButton17.Checked)
volunteerEducation = 8;
else if (radioButton18.Checked)
volunteerEducation = 9;
//end solution
string volunteerEducationPlace = addEducationPlaceTextBox.Text;
string volunteerEducationDepartmen = addEducationDepartmentTextBox.Text;
//same above
int volunteerInteresting = 0;
if (updtIntrstMdcnRadioButton.Checked)
volunteerInteresting = 1;
else if (updtIntrstSosclRadioButton.Checked)
volunteerInteresting = 2;
else if (updtIntrstLrnRadioButton.Checked)
volunteerInteresting = 3;
else if (updtIntrstTrnRadioButton.Checked)
volunteerInteresting = 4;
//end
string volunteerNotes = addNotesTextBox.Text;
int x = dataGridViewX1.SelectedRows[0].Index;
UpdateVolunteer(volunteerID, volunteerName, volunteerZone, volunteerStreet, volunteerSex, volunteerBirthday, volunteerHomePhone, volunteerWorkPhone, volunteerMobile1, volunteerMobile2, volunteerEmail, volunteerJob, volunteerAffiliation, volunteerEducation, volunteerEducationPlace, volunteerEducationDepartmen, volunteerInteresting, volunteerNotes);
showVolunteers(x);
updtIDTextBox.Text = "";
updtNameTextBox.Text = "";
updtZoneTextBox.Text = "";
updtStreetTextBox.Text = "";
updtBirthdayDateTimePicker.Value = DateTime.Now;
updtHomePhoneTextBox.Text = "";
updtWorkPhoneTextBox.Text = "";
updtMobile1TextBox.Text = "";
updtMobile2TextBox.Text = "";
updtEmailTextBox.Text = "";
updtJobTextBox.Text = "";
updtAffiliationTextBox.Text = "";
updtEducationPlaceTextBox.Text = "";
updtEducationDepartmentTextBox.Text = "";
updtNotesTextBox.Text = "";
}
catch (SqlException sql)
{
MessageBoxEx.Show(sql.Message);
}
}

How to skip to next item if current variable is null

I have a function that retrieves a list of device names and stores then in a variable. Then the next step is to get info using 1 device name per line and keep going till the loop is complete.
String text = "";
String errors = "";
for (int i = 0; i < collection.Result.Count; i++)
{
deviceNames += collection.Result[i].DeviceName + Environment.NewLine;
getvirtuals.Location = deviceNames;
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
{
try
{
LtmKey virtualKey = new LtmKey();
virtualKey.Location = virtuals.Result[v].Location;
virtualKey.LocationType = virtuals.Result[v].LocationType;
virtualKey.Key = virtuals.Result[v].Key;
virtualKey.KeyType = LtmKeyType.VirtualAddressPort;
virtualKey.AdminGroup = admingroupComboBox.Text;
var memberStatus = client.GetMemberStatus(virtualKey);
for (int j = 0; j < memberStatus.Result.Count; j++)
{
VirtualMemberStatus status = memberStatus.Result[j];
text += String.Format("{5},{4},{0},{1},{2},{3}" + Environment.NewLine, status.Member.Address, status.Member.Port, status.EffectiveStatus, status.DesiredStatus, virtualKey.Key.Replace(":", ","), DateTime.UtcNow);
toolStripProgressBar1.PerformStep();
}
}
catch
{
errors += String.Format("{0} Error Code: 2, Error occurred, check device name (case senstive) and admin group. This error may also occur due to connection loss, try again." + Environment.NewLine, DateTime.UtcNow);
}
}
this.allResultsBox.Text = text;
getallstatusButton.Enabled = true;
}
}
The problem that I am running into is that if virtuals is null the tool crashes, instead what I want to do is if virtuals = null I want to move onto the next item from the list. I have tried a if statement but it is not working the way planned, it still comes back as null.
Well this seems like a problem to start with:
if (virtuals.Result == null)
{
i++;
getvirtuals.Location = deviceNames;
for (int v = 0; v < virtuals.Result.Count; v++)
...
If virtuals.Result is null, how do you expect virtuals.Result.Count to work? I suspect you meant:
if (virtuals.Result != null)
However, I suspect you really just want:
// Keep going with the next iteration of the for loop
if (virtuals == null || virtuals.Results == null)
{
continue;
}
If all you want is to go to the next loop iteration if virtuals is null then you want
if (virtuals == null) continue;
How about just inserting:
if(virtuals == null)
continue;
right after the line
var virtuals = client.GetKnownVirtuals(getvirtuals, LtmKeyType.VirtualAddressPort);
Have you tried changing the line:
if (virtuals.Result == null)
to:
if ((virtuals != null) && (virtuals.Result != null))
If this doesn't solve your issue, then you need to indicate what the additional errors are.
if (virtuals.Result == null)
make this
if (virtuals == null)

Categories

Resources