reading from a file, input string is incorrect C# - c#

I'm trying to read a file from a .txt, the file is a few numbers. But when I run the program I'm getting input string is not in the correct format. I passed everything into integers using parse. What am I missing?
private void button1_Click(object sender, EventArgs e)
{
try
{
const int Size = 10;
int[] numbers = new int[Size];
int index = 0;
StreamReader inputFile;
inputFile = File.OpenText("Sales.txt");
while(index < numbers.Length && !inputFile.EndOfStream)
{
numbers[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach( int value in numbers)
{
listBox1.Items.Add(value);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

This is due to your input file consisting of doubles, not ints. Any non-whole number must be stored as a double or a float if you do not want to lose the numbers after the decimal point. Try the following code.
private void button1_Click(object sender, EventArgs e)
{
try
{
const int Size = 10;
double[] numbers = new double[Size];
int index = 0;
StreamReader inputFile;
inputFile = File.OpenText("Sales.txt");
while(index < numbers.Length && !inputFile.EndOfStream)
{
numbers[index] = double.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach(double value in numbers)
{
listBox1.Items.Add(value);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
However, the issue may also be that your data isn't separated by lines, but by spaces. According to your comment, this may be the case. To fix that, you would use the following code.
private void button1_Click(object sender, EventArgs e)
{
try
{
foreach (double value in File.ReadAllText("Sales.txt").Split(' ').Select((x) => (double.Parse(x))))
{
listBox1.Items.Add(value);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What this solution does is ReadAllText from the file, which automatically handles streams, opening, and closing of the file. I pass that into the Split function, which splits a single String into substrings where the parameter is found. So, if you have 123.613 7342.152 as your String, it will return you a String[] that consists of 123.613 and 7342.152. However, these values are still Strings. We still need to parse them into numbers. We can do this by using the LINQ Select operator, and passing it in a lambda that will call double.Parse(...) on the value and return it as an IEnumerable<double>.

Related

Why is my while loop not repeating as many times as my input says?

My application should get user input as well as a number of repetitions.
After it's verified as positive data, it should display results in a list box.
Results should be phrase # of reps entered.
I know I need to use a while loop but where am I going wrong. Below is what I have so far:
private void btnDisplay_Click(object sender, EventArgs e)
{
// Delcare variables
int Numberofreps;
int Count = 1;
string Phrase = txtPhrase.Text;
//Get the inputs
if (int.TryParse(txtNumberofreps.Text, out Numberofreps))
{
if (txtPhrase.Text == Phrase)
{
lstDisplay.Items.Add(txtPhrase.Text);
}
//Check to make sure its a positive value
while(Count >= 1)
{
//Display the number of reps
lstDisplay.Items.Add(txtPhrase.Text);
}
}
else
{
MessageBox.Show("Not a Positive Value");
}
You have in infinite loop since you are not changing the value of Count inside.
I would probably change the code to this:
private void btnDisplay_Click(object sender, EventArgs e)
{
// Delcare variables
int Numberofreps;
//Get the inputs
if (int.TryParse(txtNumberofreps.Text, out Numberofreps) && Numberofreps > 0)
// Note I've added a check that the Numberofreps is a positive integer.
{
while(Numberofreps > 0)
{
//Display the number of reps
lstDisplay.Items.Add(txtPhrase.Text);
Numberofreps--; // Note this line.
}
}
else
{
MessageBox.Show("Not a Positive Integer");
}
}
I suggest using for loop instead of while:
private void btnDisplay_Click(object sender, EventArgs e) {
int Numberofreps;
if (!int.TryParse(txtNumberofreps.Text, out Numberofreps))
MessageBox.Show("Not a integer Value");
else if (Numberofreps <= 0)
MessageBox.Show("Not a Positive Value");
else {
for (int i = 0; i < Numberofreps; ++i)
lstDisplay.Items.Add(txtPhrase.Text);
}
}
If you insist on while loop:
int i = 0;
while (i < Numberofreps) {
lstDisplay.Items.Add(txtPhrase.Text);
i += 1;
}

error input string was not in a correct format c#

im working in a project where it has to import excel file and show its details in 3 different data grid .i have a button with codes here.
private void btn1_Click(object sender, EventArgs e)
{
try
{
if (Convert.ToInt32(txtreg.Text) > 0)
{
for (int i = 0; i < dgResult1.Columns.Count; i++)
{
if (dgResult1.Columns[i].HeaderText == "REGHRS")
{
for (int j = 0; j < dgResult1.Rows.Count; j++)
{
if (Convert.ToInt32(dgResult1.Rows[j].Cells["REGHRS"].Value.ToString()) >= 12)
{
dgResult1.Rows[j].Cells["REGHRS"].Value = txtreg.Text;
dgResult2.Rows[j].Cells["REGHRS"].Value = Convert.ToInt32(dgResult2.Rows[j].Cells["REGHRS"].Value.ToString().Trim()) - Convert.ToInt32(txtreg.Text);
dgResult3.Rows[j].Cells["REGHRS"].Value = 0;
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
and it throws an error with input string was not in a correct format .can somebody help me .thanks
This is classic Debugging 101, and it's a good idea to learn it early in your career unless you're the coding Kwisatz Haderach, who can write bug-free code first time, every time :-)
Every time before you attempt a conversion with something like:
Convert.ToInt32(blah)
(I see four of those in your code, two on a single line), you should put in some temporary debug code (message box, or console writeline, or something) to find out what blah is actually set to. This should include the actual string, surrounded by [] characters, and the length of the string.
This will let you identify which string is failing the integer conversion. Once you've established that, the next step will be to work out why.
Handling Convert.ToInt32
your exception occurs by Convert.ToInt32(...) - you use it several times.. that means that in some point a string without a number passed to this function
my guess is that some field from the database contains null and represented by an empty string
althougth Convert.ToInt32 can deal with null values it fails on empty string values
a potential solution - use your own method:
int ConvertInt(string val)
{
return (val.IsNullOrEmpty(val)) ? 0 : int.Parse(val); // Parse aimed to deal with strings only while Convert deals withe several types
}
private void btn1_Click(object sender, EventArgs e)
{
int regNumber = 0;
bool regFlag = int.TryParse(txtreg.Text, regNumber)
if(!regFlag)
{
MessageBox.Show("Reg textbox doesn't have integer value");
return;
}
if(regNumber <= 0)
{
MessageBox.Show("Reg textbox has negative or 0 value");
return;
}
for (int i = 0; i < dgResult1.Columns.Count; i++)
{
if (dgResult1.Columns[i].HeaderText != "REGHRS")
continue;
for (int j = 0; j < dgResult1.Rows.Count; j++)
{
string regHrs = dgResult1.Rows[j].Cells["REGHRS"].Value.ToString();
int regValue = 0;
bool regCheck = int.TryParse(regHrs, out regValue)
if(!regCheck || reg < 12)
continue;
dgResult1.Rows[j].Cells["REGHRS"].Value = txtreg.Text;
//till now both converts should be okay.
dgResult2.Rows[j].Cells["REGHRS"].Value = Convert.ToInt32(dgResult2.Rows[j].Cells["REGHRS"].Value.ToString()) - Convert.ToInt32(txtreg.Text);
dgResult3.Rows[j].Cells["REGHRS"].Value = 0;
}
}
}
The error is that you are converting somewhere wrong integer values. Also you have really bad structure of the code. You should avoid nested if. I wrote how the code should probably look like. Also why catch system exceptions, no user cares about them. You should show relevant text.
Below is my opinion
private void btn1_Click(object sender, EventArgs e)
{
try
{
if (Convert.ToInt32(txtreg.Text) > 0)
{
for (int i = 0; i < dgResult1.Columns.Count; i++)
{
if (dgResult1.Columns[i].HeaderText == "REGHRS")
{
for (int j = 0; j < dgResult1.Rows.Count; j++)
{
if (Convert.ToInt32(dgResult1.Rows[j].Cells["REGHRS"].Value.ToString()) >= 12)
{
dgResult1.Rows[j].Cells["REGHRS"].Value = txtreg.Text;
dgResult2.Rows[j].Cells["REGHRS"].Value = Convert.ToInt32(dgResult2.Rows[j].Cells["REGHRS"].Value.ToString().Trim()) - Convert.ToInt32(txtreg.Text);
dgResult3.Rows[j].Cells["REGHRS"].Value = "0";//UpDate this
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

How do to add validation to my calculator in c#

I'm creating a calculator and I want to add validation code in it, so that if anything besides numbers is entered, an error message appears.
private void button4_Click(object sender, EventArgs e)
{
int R = Convert.ToInt32(textBox1.Text);
int I = Convert.ToInt32(textBox2.Text);
int number2;
if (int.TryParse(textBox1.Text, out number2))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
textBox2.Text = ("value entered is not whole number");
}
}
This is the code I am trying to use but it comes up with an error message when I enter a non-numeric value.
You are calling Convert.ToInt32 method before TryParse and that causes the exception. Don't do that, do the validation with TryParse.
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R) &&
int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
MessageBox.Show("You have entered an invalid value!");
}
}
Also you might consider using more descriptive variable names instead of E, R, I...
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R)
&& int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else { textBox3.Text = ("value entered is not whole number"); }
}
Make sure you try to parse the strings into ints with TryParse always, rather than just converting immediately... if there are letters, the conversion fails.
private void button4_Click(object sender, EventArgs e)
{
int number1;
int number2;
if (int.TryParse(textBox1.Text, out number1) && int.TryParse(textBox2.Text, out number2))
{
//do your thang (subtraction, assigning the result to TextBox3)
//return
}
else
{
MessageBox.Show("Oh no you entered something that's not an int!");
}
}
I might also add that making the value of one of your input text boxes "Value entered is not a whole number" is kind of a weird UI experience. I'd mark the textbox in red or pop up a message box or something instead, leaving the entered value in the box, in case it was some really long number like 879320!78 where they accidentally entered a weird symbol or something.

convert string to double not working?

I'd like to convert a string to a double. I know, it has been asked before, but let me finish it! :)
So I read the string in from a USB port (Arduino experiment), and I'd like to add that value to a list of doubles. The values are coming in continuously.
The problem is, when I try to convert the string to double it gives an error message that says: "The format of the incoming character chain is wrong" or something like this. I get this error message with both the parse and convert command.
What should I do?
Here's the part of the code that supposed to do the job:
namespace voltmeres{
public partial class Form1 : Form
{
List<double> lista = new List<double>();
int i;
double f;
string POT;
public Form1()
{
InitializeComponent();
serialPort1.PortName = "COM5";
serialPort1.BaudRate = 9600;
lista.Capacity = 100;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
POT =serialPort1.ReadExisting();
textBox1.Text = POT.ToString();
}
f = Convert.ToDouble(textBox1.Text);
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity=lista.Capacity + 100;
}
}
From the comments, it looks like it's a number formatting issue. Try the following:
f = Convert.ToDouble(textBox1.Text, new System.Globalization.CultureInfo("en-US"));
Try this
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
POT = serialPort1.ReadExisting();
textBox1.Text = POT.ToString();
}
if (! double.TryParse(textBox1.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out f)) return;
f = Convert.ToDouble(textBox1.Text);
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity = lista.Capacity + 100;
}
}
You should use double.TryParse instead. It will parse if it is a double, else it will not throw an exception.
if(double.TryParse(textBox1.Text,outf))
{
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity=lista.Capacity + 100;
}
}
If the above answers don't work, try 'String.valueOf(your double);' This should do the trick if your double is correct.
Another suggestion : depending on the double you have, for instance if it is a really long double, you may want to format the value before or after the conversion to take only a few digits.

Not able to count line number in richtextbox

here is my code
private void Allocation_Matrix_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
int Total_Row_Check;
Total_Row_Check = getRow();
Textbox1.Text = Convert.ToString(Total_Row_Check);
if (Total_Row_Check >= Convert.ToInt32(Total_Processes.Text))
{
MessageBox.Show("rows cannot exceed from total number of processess");
}
}
}
public int getRow()
{
int Row = 0;
string[] arLines;
int i;
arLines = Allocation_Matrix.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
for (i = 0; i < arLines.Length; i++)
{
Row++;
}
return Row;
}
i want to update TextBox1 as i hit ENTER in richtextbox from keyboard...but Textbox keeps show only FirstRow and shows One(1)
How about using RichTextBox.GetLineFromCharIndex Method? It returns, the zero-based line number in which the character index is located.
Is Allocation_Matrix your RichTextBox?
Note that RichTextBox.Text returns the text with line feed ("\n") for the line breaks, where most all other Windows controls use a carriage return, line feed ("\r\n").
So if you are calling Split on the string returned by the Text property, it won't contain any Evironment.NewLine.
try Allocation_Matrix.Text.Lines.Count() method
try this
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
var lineCount = richTextBox.Lines.Count();
numberLabel.Text = lineCount.ToString();
}

Categories