C# error message displayed based on text or number input - c#

I'm trying to write line where if text (anything other than number) typed it shows error message that it is not number and ask user to type again.
Also I have implanted that number must be 20 or higher which works fine and when ever user input less than 20 it shows error message and ask user again..
so my problem is that it shows error message for everything including number less than 20 and text.
So how can I make else statement that shows different message if text is type rather than number?
static double InputFuel() {
double fFuel;
string text;
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
//Check if fule entered is greater than 20, if not ask again
do {
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20) {
badValue = false;
}
else {
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter a number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputFuel
I tried something like this but not working
else (!int.TryParse(text, out num) {
Console.WriteLine("\n\t {0} is not a number \n\n", text);
}

Firstly I would check if input is number and after that if number is greater than 20
static double InputFuel() {
double fFuel;
string text;
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
//Check if fule entered is greater than 20, if not ask again
do {
text = Console.ReadLine();
if (!double.TryParse(text, out fFuel) {
Console.WriteLine("\n\t {0} is not a number \n\n", text);
}
else if (fFuel >= 20) {
badValue = false;
}
else {
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter a number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputFuel

You can your modify your current condition to be nested like below
if (double.TryParse(text, out fFuel)) {
if(fFuel >= 20) badValue = false;
else {
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter a number greater than 20 : ");
}
}
else {
Console.WriteLine("\n\t {0} is not a number \n\n", text);
}

If you're looking for 'more advanced' or 'more enterprise-like' way of validating user input you can create a struct or class that will do the validation and provide some information about it :
class InputValidator
{
public string Input { get; set; }
public bool IsValidInput { get; set; }
public bool IsAboveThreshHold { get; set; }
public bool IsNumber { get; set; }
public double Litres { get; set; }
public ValidationResult() { }
public ValidationResult(string text)
{
double litres; Input = text;
if (double.TryParse(text, out litres))
{
Litres = litres;
IsAboveThreshHold = litres > 20;
IsNumber = true;
}
IsValidInput = IsNumber && IsAboveThreshHold;
}
public void ShowErrorMessage()
{
if (!IsNumber)
{
Console.WriteLine($"\n\t {Input} is not a valid number \n\n");
Console.Write("Please re-enter a number greater than 20 : ");
return;
}
if(!IsAboveThreshHold)
{
Console.WriteLine($"\n\t {Input} is below the minimum value of 20 \n\n");
Console.Write("Please re-enter a number greater than 20 : ");
}
}
}
And use this class very easily :
static double InputFuel()
{
var result = new InputValidator();
Console.Write("Enter amount of fuel used in litres : ");
//Check if fule entered is greater than 20, if not ask again
while (!result.IsValidInput)
{
result = new InputValidator(Console.ReadLine());
if (!result.IsValidInput) result.ShowErrorMessage();
}
return result.Litres;
}
P.S.
While in simple cases this would be an overkill but in more complex cases that are common in enterprise projects this approach is much better to use.

Related

Try and Catch blocks not throwing anything

I have created an ArgumetException catch block and it is not throwing anything when I input something it is supposed to catch...how do I fix this? For example if I input the driver age as 15 or 81 it still goes through with out being caught and it calculates the final premium. I also would enter their state of residency that isn't Ohio or Michigan and my catch block is not catching anything. I don't know if you can understand what I'm trying to say but if you copy and paste this into your IDE and try running it your self I think you'll understand it a bit more.
Here is the code
class Program
{
static void Main(string[] args)
{
CarInsurance create = new CarInsurance();
try
{
Console.Write("Enter the age of the driver: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the state the driver lives in: ");
string residence = Convert.ToString(Console.ReadLine());
create.PremiumCalculate(age, residence);
}
catch (FormatException) // catches if user inputs a string instead of a value
{
Console.WriteLine("You didn't enter a numeric value for the age of the driver!");
}
}
}
class CarInsurance
{
public int driverAge { get; set; } // gets and sets driver age
public string residency { get; set; } // gets and sets residency
public int totalPremium;
public int GetPremium() // gets the premium ***readonly***
{
return totalPremium;
}
public void PremiumCalculate(int age, string residency) // main method for CarInurance class
{
int premiumOhio = 100;
int premiumMichigan = 250;
try
{
if (residency == "MI")
{
int total = (100 - age) * 3 + premiumMichigan;
Console.WriteLine("Your premium is {0}", total.ToString("C"));
}
if (residency == "OH")
{
int total = (100 - age) * 3 + premiumOhio;
Console.WriteLine("Your premium is {0}", total.ToString("C"));
}
}
catch (ArgumentException)
{
if (age < 16 && age > 80)
{
Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
}
if (residency != "OH" && residency != "MI")
{
Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
}
}
}
}
The final try-catch block at the bottom of the code is what I am having a problem with.

How can I apply the `|` operand to a string?

I am having trouble with this line of code right here...why am I being prompted with this error? I am getting an error saying "Operator '|' cannot be applied to operands of type 'bool' and 'string' How do check if my residency variable is not equal to these 2 strings I have listed in the if statement?
catch (ArgumentException)
{
if (age > 16 | age > 80)
{
Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
}
if (residency != "OH" | "MI")
{
Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
}
}
Here is the full code if you want to get a better idea of what I am trying to execute.
class Program
{
static void Main(string[] args)
{
CarInsurance create = new CarInsurance();
Console.Write("Enter the age of the driver: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the state the driver lives in: ");
string residence = Convert.ToString(Console.ReadLine());
create.PremiumCalculate(age, residence);
}
}
class CarInsurance
{
public int driverAge { get; set; }
public string residency { get; set; }
public int totalPremium;
public int GetPremium()
{
return totalPremium;
}
public void PremiumCalculate(int age, string residency)
{
int premiumOhio = 100;
int premiumMichigan = 250;
try
{
if (residency == "MI")
{
int total = (100 - age) * 3 + premiumMichigan;
Console.WriteLine("Your premium is {0}", total.ToString("C"));
}
if (residency == "OH")
{
int total = (100 - age) * 3 + premiumOhio;
Console.WriteLine("Your premium is {0}", total.ToString("C"));
}
}
catch (ArgumentException)
{
if (age > 16 | age > 80)
{
Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
}
if (residency != "OH" | "MI")
{
Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
}
}
}
}
You should apply it between two conditions, not values. Note
if (residency != "OH" || residency != "MI")
Note, however, that this condition will always return true. You probably meant to use &&:
if (residency != "OH" && residency != "MI")
Let me explain the issue first. Here residency != "OH" | "MI", you are evaluating residency != "OH" and this works and produces bool. Then produced bool fails against | "MI" because operator | is invalid for strings.
If you had 2 strings, you would get
Operator '|' cannot be applied to operands of type 'string' and 'string'
One way to fix it is
using System.Linq;
. . ..
var exclusionList = new [] {"OH","MI"};
if (!exclusionList.Contains(residency))
How about something like this. First, I start off by listing all states (yeah, you only care about two of them, but any of them is a valid state):
public enum ResidentState
{
AL,
AK,
AZ,
AR,
CA,
CO,
CT,
DE,
FL,
GA,
HI,
ID,
IL,
IN,
IA,
KS,
KY,
LA,
ME,
MD,
MA,
MI,
MN,
MS,
MO,
MT,
NE,
NV,
NH,
NJ,
NM,
NY,
NC,
ND,
OH,
OK,
OR,
PA,
RI,
SC,
SD,
TN,
TX,
UT,
VT,
VA,
WA,
WV,
WI,
WY,
}
Then I start my car insurance class:
class CarInsurance
{
public int DriverAge { get; private set; }
public ResidentState Residency { get; private set; }
public int TotalPremium { get; private set; }
private bool _ageOk = false;
private bool _residencyOk = false;
}
It has publicly readable properties for DriverAge, ResidentState and TotalPremium. They can only be set from within the class. It also has a few bookkeeping flags for age and residency validity.
Then, I add a couple of member functions to that class to set the DriverAge and Residency. They do error checking. They both have the same pattern. They will return false unless you set them correctly:
public bool SetResidency(ResidentState residency)
{
if (residency != ResidentState.OH && residency != ResidentState.MI)
{
Console.WriteLine("You can only enter states of OH or MI");
return false;
}
Residency = residency;
_residencyOk = true;
return true;
}
public bool SetDriverAge(int age)
{
if (age < 16 || age > 80)
{
Console.WriteLine("The driver's age must between 16 and 80.");
return false;
}
_ageOk = true;
DriverAge = age;
return true;
}
If the caller is using these correctly, then _ageOk and _residencyOk will be true. They may be false if not.
Then I create the CalculatePremium function to that class (and a few constants) (note, I renamed it to be verb-noun, I think it makes more sense):
private const int PremiumOhio = 100;
private const int PremiumMichigan = 250;
public int CalculatePremium()
{
if (!_residencyOk)
{
throw new ArgumentException("The driver's residency must first be entered, and only Ohio and Michigan are valid states");
}
if (!_ageOk)
{
throw new ArgumentException("The driver's age must first be entered, and it must be between 16 and 80");
}
int premium;
switch (Residency)
{
case ResidentState.MI:
premium = PremiumMichigan;
break;
case ResidentState.OH:
premium = PremiumOhio;
break;
default:
premium = 10_000;
break;
}
TotalPremium = (100 - DriverAge) * 3 + premium;
Console.WriteLine($"Your total premium is {TotalPremium:C}");
return TotalPremium;
}
Finally, I wrote the Program class that has the Main function:
class Program
{
static void Main(string[] args)
{
CarInsurance insurance = new CarInsurance();
bool ageOk = false;
do
{
Console.Write("Enter the age of the driver: ");
var response = Console.ReadLine();
ageOk = int.TryParse(response, out var age);
if (!ageOk)
{
Console.WriteLine("You must enter an integer for age");
}
else
{
ageOk = insurance.SetDriverAge(age);
}
} while (!ageOk);
bool stateOk = false;
do
{
Console.Write("Enter the state the driver lives in: ");
var stateStr = Console.ReadLine();
stateOk = Enum.TryParse<ResidentState>(stateStr, true, out var state);
if (!stateOk)
{
Console.WriteLine($"The state you entered ({stateStr}) is not a valid two-letter state abbreviation");
}
else
{
stateOk = insurance.SetResidency(state);
}
} while (!stateOk);
var premium = insurance.CalculatePremium();
}
}
Note that I check that the entered data is a valid integer (or a valid state abbreviation) in this code. Then I check (using the Insurance class) that it is valid for this calculation. As it's written, it will not cause either of the exceptions within CalculatePremium to be thrown. However, it might make sense to wrap the call to CalculatePremium in a try/catch. I'll leave that up to you - you really need to read up on exceptions.
I wrote this is a way (and explained it in a way), that will allow you to explore some of the features of the language. Step through it in the debugger. Enter invalid entries for both quantities (something that's not an integer, and then something that's out of range for age, and something that's not a state and then not either MI or OH) and see what happens. Try calling calculate premium with invalid values and see what happens (and try to catch the result).

How to add a variable in a while loop with the same variable in a loop (if possible)

What I have here is a small console app I'm wanting the user to type in their monthly salary then their "Expenses" To calculate how much money they have over the month once they take away their expenses (A calculator that tells the user how much money they have monthly once all bills are paid). I'd like to take away from int Salary. I want the expenses to keep populating until the user types "false", in the bool FinishedAdding currently the variable Expenses only holds one value, I want to add all Expenses then subtract from Salary. Am I doing this correctly or is this the wrong approach?
string NewLine = "\n";
bool Finished = false;
var Expenses = default(int);
Console.WriteLine("Enter you earn a month (after tax");
int Salary = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(NewLine);
if (Finished != true)
{
while (Finished == false)
{
Console.WriteLine("What are your expenses");
Expenses = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You are finished?");
bool FinishedAdding = Convert.ToBoolean(Console.ReadLine());
if (FinishedAdding == true)
{
break;
}
}
}
Console.WriteLine(NewLine);
Console.WriteLine("Your total is: " + (Expenses - Salary));
Couple changes I made:
1) Most importantly: Expenses += will add what they enter each time to the amount they entered previously. This will be your total expenses that you can then subtract from Salary.
2) Instead of using a separate variable for Finished, just set the Finished variable to whether or not they enter "true" or "false".
3) No need for an if and break statement, just let the while criteria check the Finished variable.
string NewLine = "\n";
bool Finished = false;
var Expenses = default(int);
Console.WriteLine("Enter you earn a month (after tax)");
int Salary = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(NewLine);
while (Finished == false)
{
Console.WriteLine("What are your expenses");
Expenses += Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You are finished?");
Finished = Convert.ToBoolean(Console.ReadLine());
}
Console.WriteLine(NewLine);
Console.WriteLine($"Your total is: {(Salary - Expenses)}");
Let's implement the routine step by step. We can start from reading decimal (which better fits financial data like Salary)
// Either enter valid decimal value or press enter (for exit)
private static bool TryReadDecimalOrExit(string title, out decimal value) {
value = 0m;
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
return false;
if (decimal.TryParse(input, out value))
return true;
Console.WriteLine("Sorry, invalid value. Please, try again");
}
}
private static decimal ReadDecimal(string title) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
string input = Console.ReadLine();
if (decimal.TryParse(input, out value))
return value;
Console.WriteLine("Sorry, invalid value. Please, try again");
}
}
Time to loop:
decimal Salary = ReadDecimal("Enter you earn a month (after tax");
Decimal Expenses = 0m;
// While not exited, ask for a new expense
while (TryReadDecimalOrExit("What are your expenses", out var expense))
Expenses += expense;
Console.WriteLine("Your total is: {Salary - Expenses:c2}");
With
Expenses = Convert.ToInt32(Console.ReadLine());
you are assigning a value to Expenses with each iteration. Since the expenses of the user do not equal the last amount they spent, but the summed amount, you'd have to sum up the expenses
Expenses = Expenses + Convert.ToInt32(Console.ReadLine());
This can be simplified with +=, which is basically "add a value to the contents of a variable and assign the new value to the variable". This yields
Expenses += Convert.ToInt32(Console.ReadLine());
On a side note
There is no error handling. Your program will crash if I enter e.g. ei19 as the amount. While the answer of Dmitry provides an approach to error handling in your program, it will exit as soon as you type something that is not a number. You might want to check whether the input is valid ans display an error message
while(!Finish)
{
var input = ReadInput("Your message");
if(ShouldExit(input))
{
Finish = true;
}
else if(IsValidAmount(input))
{
Expenses = input.Amount;
}
else
{
WriteErrorMessage("Your error message");
}
}
if input being of type UserInput for example
class UserInput
{
// ...
public bool Finished { get; }
public Decimal Amount { get; }
}
just for the gist of it.
string NewLine = "\n";
bool Finished = false;
var Expenses = default(int);
Console.WriteLine("Enter you earn a month (after tax");
int Salary = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(NewLine);
while (!Finished)
{
Console.WriteLine("What are your expenses");
Expenses += Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You are finished?");
Finished = Convert.ToBoolean(Console.ReadLine());
}
Console.WriteLine(NewLine);
Console.WriteLine("Your total is: " + (Salary - Expenses));

Converting a program with just static methods to one that uses objects instead

The program works in its current for but I would like to make it more object oriented like its design using constructors and such but I don't know where to start and how to make it work. I would like your insight and examples on how you would accomplish this task? Here is a sample UML for what I am trying to do.
Original Design
public static class IsbnConsole
{
public static void Main(string[] args)
{
Console.Write("Enter a valid 10 digit ISBN Number ");
string isbn = checkIsbnClass.DestabilizeIsbn(Console.ReadLine()); // Normalizes the input and puts it on string "str"
if (isbn.Length > 10 || isbn.Length < 9) // If the string length is greather than 10, or smaller than 9
{
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
Console.ReadLine();
}
else if (isbn.Length == 10) // If the length is 10
{
if (checkIsbnClass.CheckNumber(isbn)) // If function CheckNum return "true"...
Console.WriteLine("The number you have entered is a Valid ISBN");
else // If it returns "false"...
Console.WriteLine("The number you have entered is not a valid ISBN try again.");
Console.ReadLine();
}
else // Else (If the number is NOT greater than 10 or smaller than 9, NOR is it 10 -> If the number is 9)
{
Console.WriteLine("The Check digit that corresponds to this ISBN number is " + checkIsbnClass.CheckIsbn(isbn) + "."); // Print the checksum digit
Console.ReadLine();
}
public static class checkIsbnClass
{
public static string CheckIsbn(string isbn) // Calculates the 10th digit of a 9-digits partial ISBN number
{
int sum = 0;
for (int i = 0; i < 9; i++) // For each number...
{
sum += int.Parse(isbn[i].ToString()) * (i + 1); // ...Multiply the number by it's location in the string
}
if ((sum % 11) == 10) // If the remainder equals to 10...
{
return "x"; // Output X
}
else // If it does not equal to 10...
{
return (sum % 11).ToString(); // Output the number
}
}
public static bool CheckNumber(string isbn) // Checks if the checksum digit is correct
{
if (isbn[9].ToString() == CheckIsbn(isbn)) // If the 10th digit of the number is the same as the calculated digit...
return true;
else // If they're not the same...
return false;
}
public static string DestabilizeIsbn(string isbn) // replace the string
{
return isbn.Replace("-", "").Replace(" ", "");
}
Newly Designed Method Using Constructors
public class isbn
{ //attributes
private string isbnNum;
//method
public string GetIsbn()
{
return this.isbnNum;
}
//constructor
public isbn()
{
Console.Write("Enter Your ISBN Number: ");
this.isbnNum = Console.ReadLine();
}//end default constructor
//method
public string displayISBN()
{
return this.GetIsbn();
}
public static void Main(string[] args)
{
//create a new instance of the ISBN/book class
isbn myFavoriteBook = new isbn();
//contains the method for checking validity
bool isValid = CheckDigit.CheckIsbn(myFavoriteBook.GetIsbn());
//print out the results of the validity.
Console.WriteLine(string.Format("Your book {0} a valid ISBN",
isValid ? "has" : "doesn't have"));
Console.ReadLine();
}
public static class CheckDigit
{ // attributes
public static string NormalizeIsbn(string isbn)
{
return isbn.Replace("-", "").Replace(" ", "");
}
public static bool CheckIsbn(string isbn) // formula to check ISBN's validity
{
if (isbn == null)
return false;
isbn = NormalizeIsbn (isbn);
if (isbn.Length != 10)
return false;
int result;
for (int i = 0; i < 9; i++)
if (!int.TryParse(isbn[i].ToString(), out result))
return false;
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (i + 1) * int.Parse(isbn[i].ToString());
int remainder = sum % 11;
if (remainder == 10)
return isbn[9] == 'X';
else
return isbn[9] == (char)('0' + remainder);
}
public static class IsbnConsole
{
public static void Main(string[] args)
{
Console.Write("Enter a valid 10 digit ISBN Number ");
string isbn = checkIsbnClass.DestabilizeIsbn(Console.ReadLine()); // Normalizes the input and puts it on string "str"
Isbn isbn = new Isbn(Console.In)
if (!isbn.CheckLength())
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
}
else if (isbn.HasCheckDigit)
{
if (isbn.CheckNumber(isbn))
Console.WriteLine("The number you have entered is a Valid ISBN");
else
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
}
else
{
Console.WriteLine("The Check digit that corresponds to this ISBN number is " + isbn.GetCheckDigit(isbn) + "."); // Print the checksum digit
}
Console.ReadLine();
}
public class Isbn
{
public Isbn(TextReader cin)
{
/// do stuff here.
}
public bool CheckLength()
{
/// do stuff here.
}
public bool HasCheckDigit { get { ..... } }
public int GetCheckDigit() {..... }
public bool CheckNumber() {......}
}
I do think the original design makes sense. I mean the ISBN has no other purpose than to be checked. I don't see any benefit in trying to materialize it as an instance class.
But just for academic purposes, you may ask yourself several questions here:
- Do you want to materialize the ISBN itself ? Create an ISBN class containing properties for its value and methods for the checks (this is James Curran's solution)
- Do you want to materialize the fact that you check an ISBN ? Create an ISBNChecker class that will contain methods to perform the checks
- Both ? an ISBN instance will be created from the Console input and pass as a parameter to the ISBNChecker instance.
By materialize, I mean "create an instance class"

Get input from console into a form

I want to see how I can get the value entered in this console application to work inside a form textbox how can I do this?
Example entering 00000000 in console to be as if it were entered in the form so I guess I want them to be separate but work seamless any ideas. I cant figure out how to get the textbox to get the contents from the Console.Readline() of the console application.
This is and example of how I am trying to get it to work
public static void Main(string[] args)
{
Console.Write("Enter a valid 10 digit ISBN Number ");
string isbn = isbnChecker.DestabilizeIsbn(Console.ReadLine()); // Normalizes the input and puts it on string "str"
if (isbn.Length > 10 || isbn.Length < 9) // If the string length is greather than 10, or smaller than 9
{
Console.WriteLine("The number you have entered is not a valid ISBN try again."); // Print invalid number
Console.ReadLine();
}
else if (isbn.Length == 10) // If the length is 10
{
if (isbnChecker.CheckNumber(isbn)) // If function CheckNum return "true"...
Console.WriteLine("The number you have entered is a valid ISBN");
else // If it returns "false"...
Console.WriteLine("The number you have entered is not a valid ISBN try again.");
Console.ReadLine();
}
else // Else (If the number is NOT greater than 10 or smaller than 9, NOR is it 10 -> If the number is 9)
{
Console.WriteLine("The Check digit that corresponds to this ISBN number is " + checkIsbnClass.CheckIsbn(isbn) + "."); // Print the checksum digit
Console.ReadLine();
}
}
public static class isbnChecker
{
public static bool CheckNumber(string isbn) // Checks if the checksum digit is correct
{
if (isbn[9].ToString() == checkIsbnClass.CheckIsbn(isbn)) // If the 10th digit of the number is the same as the calculated digit...
return true;
else // If they're not the same...
return false;
}
public static string DestabilizeIsbn(string isbn) // replace the string
{
return isbn.Replace("-", "").Replace(" ", "");
}
}
[1]: http://i.stack.imgur.com/bAcDJ.jpg
public static string CheckIsbn(string isbn) // Calculates the 10th digit of a 9-digits partial ISBN number
{
int sum = 0;
for (int i = 0; i < 9; i++) // For each number...
{
sum += int.Parse(isbn[i].ToString()) * (i + 1); // ...Multiply the number by it's location in the string
}
if ((sum % 11) == 10) // If the remainder equals to 10...
{
return "x"; // Output X
}
else // If it does not equal to 10...
{
return (sum % 11).ToString(); // Output the number
}
}
public static bool CheckNumber(string isbn) // Checks if the checksum digit is correct
{
if (isbn[9].ToString() == CheckIsbn(isbn)) // If the 10th digit of the number is the same as the calculated digit...
return true;
else // If they're not the same...
return false;
}
public static string DestabilizeIsbn(string isbn) // replace the string
{
return isbn.Replace("-", "").Replace(" ", "");
}
}
public partial class IsbnForm : Form
{
public IsbnForm()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.xInputTextBox.Text = "Enter a Valid ISBN";
}
}
Create an instance of the form and pass in the variable you store when you do a readline into the textbox.
IsbnForm form = new IsbnForm();
You can pass the text in a few ways, via method:
//In the IsbnForm class
public SetTextboxText(String Text) { textbox.text = Text; }
//In the console application
form.SetTextboxText(isbn);
a variable such as:
//In the IsbnForm class
public String TextboxText { set { textbox.text = value; } }
//In the console application
form.TextboxText = isbn;
or just making the textbox control public, and then changing the value via
//In the console application.
form.textbox.text = isbn;
You'll need to keep the console program running when you show your form, either by having a readline, a loop that breaks when the form is closed or possibly using ShowDialog instead of Show.
See which one works properly and how you'd expect it to work.
form.Show();
Console.Readline();
or
while(FormRunning == false) { }
or
form.ShowDialog();

Categories

Resources