I'm trying to get data from a file and store them in an array then display the data in a listbox the find then sum and display it in a text box. Here's my code and it doesn't work. I'm not sure what i'm doing wrong.
private void findClick(object sender, EventArgs e)
{
int sum;
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
using (StreamReader InputFile = new StreamReader(ofd.FileName))
{
while (InputFile.EndOfStream == false)
{
int[] array = new int[listBox.Items.Count];
for (int i = 0; i < listBox.Items.Count; i++)
{
// array[i] = Convert.ToInt32(listBox.Items[i].ToString());
array[i] = int.Parse(listBox.Items[i].ToString());
sum = array.Sum();
TotalAmtlabel.Text = sum.ToString("N0");
TotalNumberslabel.Text = listBox.Items.Count.ToString();
TotalAmountlabel.Text = string.Format("{0:N0}", sum);
}
}
}
}
}
}
listBox.Items.AddRange(File.ReadAllLines(ofd.FileName));
Try this and modify according to your needs:
string[] amounts = File.ReadAllLines(ofd.FileName);
int currentSum = 0;
int totalSum = 0;
ListItem[] amountItems = new ListItem[amounts.Length];
for (int i = 0; i < amounts.Length; i++)
{
if (int.TryParse(amounts[i], out currentSum))
{
totalSum += currentSum;
}
amountItems[i] = amounts[i];
}
listBox.Items.AddRange(amountItems);
TotalAmountlabel.Text = string.Format("{0}", totalSum);
You can also datasource to bind the list. Please go through below MSDN references once atleast to understand security cautions:
ListItem
ListBox
Related
So I'm trying to remove all even numbers from the generated random list I created. But this message keeps showing up: "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
I don't know what I'm doing wrong. What do I need to change?
public partial class Form2 : Form
{
ArrayList array = new ArrayList();
int count = -1;
int[] numbers = new int[5];
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random randNum = new Random();
for (int i = 0; i < 5; i++)
{
numbers[i] = randNum.Next(-100, 100);
array.Add(numbers[i]);
richTextBox1.Clear();
}
for (int i = 0; i <= count; i++)
{
//displays random numbers to rich textbox
richTextBox1.AppendText(array[i].ToString() + '\n');
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (int i in array)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Your code in Button2_click is wrong. You are using foreach loop and then trying to access the index of array using its elements value.
change your second button code with following code
for (int i = 0; i < array.Count; )
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
else {
i++;
}
}
foreach (var item in array)
{
richTextBox1.Text = item +"\n";
}
You should change your enumeration like:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < array.Count; i++)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Using LINQ you can achieve this easily.
var oddArray = array.Where(a => a % 2 != 0);
richTextBox1.Text = string.Join(", ", oddArray);
PS - You just need to add a namespace i.e. System.Linq
namespace Files_and_Arrays_II
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
StreamReader inputFile;
int doctor = 0;
double total = 0, average_sys = 0;
string name, DocN;
string[] doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
int[] systolic = new int[5];
int[] diastolic = new int[5];
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(openFile.FileName);
while (!inputFile.EndOfStream)
{
name = inputFile.ReadLine();
for (int i = 0; i < 5; i++)
{
systolic[i] = int.Parse(inputFile.ReadLine());
diastolic[i] = int.Parse(inputFile.ReadLine());
}
//Calculates average for systolic
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
average_sys = total / 5;
doctor = int.Parse(inputFile.ReadLine());
DocN = doctors[doctor];
listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);
}
}
}
}
}
This is the file it is getting it from
When running the program I get the following averages for systolic: 184.6 (correct), 312 (wrong).
I've tried resetting the array at the end of the loop but that solves nothing
Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.
Like this:
string name = inputFile.ReadLine();
//Calculates average for systolic
double total = 0;
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
double average_sys = total / 5;
int doctor = int.Parse(inputFile.ReadLine());
string DocN = doctors[doctor];
listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);
Even better, use var instead of setting the variable type in two places and risking getting it wrong.
You're not resetting your variables for total and average for the second set of measurements.
protected void Button_Upload_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~/Data/" + FileUpload1.FileName);
string[] readtext = File.ReadAllLines(path);
var a = readtext;
List<string> strList = new List<string>();
foreach (string s in readtext)
{
strList.Add(s);
}
ListBox1.DataSource = strList;
ListBox1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
var b = ListBox1.SelectedIndex;
var a = ListBox1.SelectedValue.ToString();
if (b < 0)
{
// no ListBox item selected;
return;
}
StringBuilder jumbleSB = new StringBuilder();
jumbleSB.Append(a);
Random rand = new Random();
int lengthSB = jumbleSB.Length;
for (int i = 0; i < lengthSB; ++i)
{
int index1 = (rand.Next() % lengthSB);
int index2 = (rand.Next() % lengthSB);
Char temp = jumbleSB[index1];
jumbleSB[index1] = jumbleSB[index2];
jumbleSB[index2] = temp;
}
Console.WriteLine(jumbleSB);
TextBox1.Text = ListBox1.Text.ToString();
//TextBox1.Text = ListBox1.Text.Insert(jumbleSB);
Here I need to Jumble the values which selected by User. When User selects a Value it has to jumble and has to come to Textbox. I am not able to displaying the Jumble values. Any help Please...??
Console.WriteLine(jumbleSB.ToString());
I have a code where I load up a text file and save it as an array. The array contains a list of numbers with some of the numbers being duplicated. In my code I first loop through the array and replace all duplicated numbers with a -1. Then I plan on deleting all the -1 values from my array. The remaining array values (non duplicates) are then copied on to a new array to be outputted.
However I keep getting an error when I attempt to delete the -1 values from my array (see code below). I don't know why this is happening so if anyone knows anything please let me know!
P.S. This is school project so I can only use loops and if statements, not things like LINQ or foreach, etc.
public partial class Form1 : Form
{
//Global Variable
int[] Original;
public Form1()
{
InitializeComponent();
}
//Exit Application
private void mnuExit_Click_1(object sender, EventArgs e)
{
this.Close();
}
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//Code to Load the Numbers From a File
OpenFileDialog fd = new OpenFileDialog();
//Open the File Dialog and Check If A File Was Selected
if (fd.ShowDialog() == DialogResult.OK)
{
//Open File to Read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
//Go Through Text File
for (int i = 0; i < Records; i++)
{
Original[i] = int.Parse(sr.ReadLine());
}
}
}
private void btnOutput_Click(object sender, EventArgs e)
{
//Store Original Array
string Output = "Original \n";
//Output Original Array
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
//Create TempArray
int[] TempArray = new int[Original.Length];
//Set TempArray Equal to Original Array
for (int i = 0; i < Original.Length; i++)
{
TempArray[i] = Original[i];
}
//Duplicate Number Counter
int Counter = 0;
//Loop Through Entire Array
for (int i = 0; i < TempArray.Length; i++)
{
for (int j = i + 1; j < TempArray.Length; j++)
{
//Replace Duplicate Values With '-1'
if (TempArray[i] == TempArray[j])
{
TempArray[j] = -1;
Counter++;
}
}
}
//Set Size of Original Array
Original = new int[Original.Length - Counter];
//Remove -1 Values
//Index Counter
int Index = 0;
//error starts
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[Index] = TempArray[i];
Index++;
}
}
//error ends
//Final Output -- The New Array
Output = Output + "Original Without Duplicates\n";
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
lblOutput.Text = Output;
}
}
}
Reverse the line TempArray[i] = Original[Index]; to Original[Index] = TempArray[i];
The only thing you need to do in this case would be
Original = new int[Original.Length - (Counter-1)];
and yes you need to change the code to assign the values to Original instead of TempArray.
//error starts
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[Index] = TempArray[i];
Index++;
}
}
//error ends
Let's say you have three 3's in your array. In the outer loop when you iterate and come across a 3, you set the other two 3's to -1. Now you come across the first -1 which earlier was a 3 and you have already set the last 3 to -1. Now you search for duplicates and wrongly calculate your number of duplicates in the Duplicate Number Counter (called Counter) because for you -1 is a duplicate of -1.
So, what you can do is this:
First only set all duplicates to -1 and then count the number of -1's by looping through the array again. This way you will set correctly the size of non-duplicated array elements.
To set all dups to -1:
for (int outerIndex = 0; outerIndex < Original.Length; outerIndex++)
{
var currentElement = Original[outerIndex];
for (int innerIndex = outerIndex + 1; innerIndex < Original.Length; innerIndex++)
{
if (Original[innerIndex] == currentElement) Original[innerIndex] = -1;
}
}
To get the count of non-repeating elements now:
var counter = 0;
for (int index = 0; index < Original.Length; index++)
{
if (Original[index] != -1) counter++;
}
Creating non-duplicated elements' array:
var newArrayIndex = 0;
var newArray = new int[Original.Length - counter]; //Calculated counter above
for(int i = 0; i < Original.Length; i++)
{
if (Original[i] != -1) newArray[newArrayIndex++] = Original[i];
}
//Finally, not good programming practice, but
//you can set Original to this newArray if you like...
Original = newArray;
i have a 10x10 text box ( 100 of them )
I write this code to write into text file :
foreach (Control control in Panel1.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
if (string.IsNullOrEmpty(textBox.Text)) // ignore this
{
textBox.Style["visibility"] = "hidden";
}
textBox.Enabled = false;
if (numberofCommas > 8)
{
stringWriter.Write(textBox.Text);
numberofCommas = 0;
}
else
{
stringWriter.Write("," + textBox.Text );
numberofCommas++;
recordsWritten++;
}
if (recordsWritten == 10)
{
stringWriter.WriteLine();
recordsWritten = 0;
}
else
{
}
From the above i want to have 10 rows of 9 commas in the text file but instead i have 9 rows of 10 commas in the text file , is my code logic wrong? because i have been looking it for hours , i still couldn't solve it . sorry if my logic is bad , i am new to programming.
I think that you should increment recordsWritten in the last step:
if (numberofCommas > 8)
{
stringWriter.Write(textBox.Text);
numberofCommas = 0;
recordsWritten++;
}
Here is a better way to do it using Linq:
var textBoxes = Panel1.Controls.OfType<TextBox>().Select((t, i) => new { TextBox = t, Index = i }).ToList();
foreach (var tb in textBoxes)
{
if (string.IsNullOrEmpty(tb.TextBox.Text))
tb.TextBox.Style["visibility"] = "hidden";
tb.TextBox.Enabled = false;
}
foreach (var line in textBoxes.GroupBy(e => e.Index / 10)
.Select(e =>
string.Join(", ",
e.Select(a => a.TextBox.Text).ToArray())))
stringWriter.WriteLine(line);
I wouldn't recommend you to use 100 TextBox objects, you can use a DataGridView binded to a DataTable with 10 rows and 10 columns. You can still edit your data and save it to a file.
Try the below code
StringWriter stringWriter1 = new StringWriter();
DataTable dataTable1 = new DataTable();
private void Form1_Shown(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
int i;
for (i = 0; i < 10; i++)
{
dataTable1.Columns.Add("Column" + (i + 1), typeof(string));
}
for (i = 0; i < 10; i++)
{
DataRow dataRow1 = dataTable1.NewRow();
dataTable1.Rows.Add(dataRow1);
}
dataGridView1.DataSource = dataTable1;
}
private void button1_Click(object sender, EventArgs e)
{
string rowString = "";
int i,j;
for (i = 0; i < 10; i++)
{
rowString = "";
for (j = 0; j < 10; j++)
{
if (dataTable1.Rows[i][j].ToString().Contains(",") == true)
{
//Enclosing the field data inside quotes so that it can
//be identified as a single entity.
rowString += "\"" + dataTable1.Rows[i][j] + "\"" + ",";
}
else
{
rowString += dataTable1.Rows[i][j] + ",";
}
}
rowString = rowString.Substring(0, rowString.Length - 1);
stringWriter1.WriteLine(rowString);
}
}
you just need to add a DataGridView onto your Form.