Summarize all numbers of a column in Listview - c#

Edit: I found the solution myself. Its
textBoxNettobetrag.Text = Convert.ToString(19,90 * i);
Please close the thread. Thx!
I would like to easily sum up all numbers in the second column of my listView1. No whole numbers, but currency. Screenshot: listView1
Can't quite figure out how to do get the values out now. Can anyone help me out? New into programming and learning everyday. Thank you very much!
string[] arr = new string[2];
arr[0] = "Sicherheitshelm";
arr[1] = "19,90";
ListViewItem lvi = new ListViewItem(arr);
listView1.Items.Add(lvi);
for(int i = 0; i < listView1.Items.Count; i++) {
listView1.Items[i].SubItems[1].ToString();

You want to add up all SubItems, so you'll need a loop for this as well. To add up all the values, you have to convert them into a numeric value, int for example, and add them up.
You can use TryParse for this. It returns false, if the string cannot be converted, and true otherwise.
int totalSum = 0;
for (int i = 0; i < listView1.Items.Count; i++)
{
for (int j = 0; j < listView1.Items[i].SubItems.Count; j++)
{
int subItemValue = 0;
if(int.TryParse(listView1.Items[i].SubItems[j], out subItemValue))
{
totalSum += subItemValue;
}
}
}

Related

How to load data into program as double? (not string) in c# (window form application - visual studio)

I dont know how to ask, but i want to load data in double not in string as you can see in the code. Can i change them in double? i want to store them in array because i want to find maximum value from the data. cannot find them in string.
private void button1_openfile_Click(object sender, EventArgs e)
{
//load data from text file
string[] lines = File.ReadAllLines(#"C:\Users\Siti Nurhazwani\Desktop\table.txt");
string[] values;
for (int i = 0; i < lines.Length; i++)
{
values = lines[i].ToString().Split('/');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j];
}
table.Rows.Add(row);
}
}
can someone share code to me how to change the string to double? please use simple terms i am a beginner in c#.
Change these lines in your code to double.
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j];
}
Instead
double[] row = new double[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = Convert.ToDouble(values[j]);
}
I'm not sure if I understood your question correctly. Can you do the change from string to double inside the loop? If so, this should be quite easy to solve, try this for example:
var result = Convert.ToDouble(originalValue)
https://learn.microsoft.com/en-us/dotnet/api/system.convert.todouble?view=net-5.0

Save the sum of each row of a matrix into an array

I have a matrix and I want to return an array containing as elements the sum of each row elements of the matrix.
int [] sum;
for (var i = 0; i < m; i++)
{
for (var j = 0; j < result.Pages[i].Actual.Count; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}
This is how I tried to do it but seems it is not working. Any ideas?
Use var m = a.GetLength(0); to get number of rows, and var n = a.GetLength(1); to get number of columns.
now that looks like a different story after you edit:
Actually the first problem would be a NullreferenceException because int[]sum is not initialized!
Anyway, so it seems that you have an array of arrays. In this case you would need the Length of the Pages array to save your results. The first loop iterates over it using i and will run until result.Pages.Length. For each i you have correctly implemented a second loop where you sum up the result.
int [] sum = new int[result.Pages.Length];
for (var i = 0; i < result.Pages.Length; i++)
{
for (var j = 0; j < result.Pages[i].Actual.Length; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}
If you collections are List's then you need to use Count instead of Length
The Linq solution would look like this:
int [] sum = result.Pages.Select(x=>x.Sum()).ToArray();
EDIT:
double? means that you have a nullable data type. This is different from the normal double. Furthermore the default value will be null That means that you need to initialize the value at position i in sum before you add up values, otherwise the result will be null.
double? [] sum = new double?[result.Pages.Length];
for (var i = 0; i < result.Pages.Length; i++)
{
sum[i] = 0;
for (var j = 0; j < result.Pages[i].Actual.Length; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}

How do you retrieve inputted text from a textbox array?

I am creating a calculator where the user enters a number into a textbox specifing how many inputs (textboxes) the user wants to have (Code not shown). I have used a textbox array to create these textboxes. The problem comes when I want to get the text from these textboxes to perform the calculations, the code I have written so far for this is shown below:
int n;
TextBox[] textBoxes;
Label[] labels;
double[] values;
public void GetValue()
{
n = Convert.ToInt16(txtInputFields.Text);
values = new double[n];
textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
}
}
I am unsure what to put in the for loop for this; I have tried the following:
values[n] = Convert.toDouble(textBoxes[n].Text);
but it gives me the error: Index was outside the bounds of the array.
I am new to C# and programming in general so any help would be much appreciated.
Thanks.
EDIT: Code to create textboxes is shown here:
public void InstantiateTextFields()
{
n = Convert.ToInt16(txtInputFields.Text);
int posLeft = 100;
textBoxes = new TextBox[n];
labels = new Label[n];
// Creates number of inputs and labels as specified in txtInputFields (n).
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
textBoxes[i].Top = 100 + (i * 30);
textBoxes[i].Left = posLeft;
textBoxes[i].Name = "txtInput" + (i + 1);
labels[i] = new Label();
labels[i].Top = 100 + (i * 30);
labels[i].Left = posLeft - 50;
labels[i].Text = "Input " + (i + 1);
labels[i].Name = "lblInput" + (i + 1);
}
for (int i = 0; i < n; i++)
{
this.Controls.Add(textBoxes[i]);
this.Controls.Add(labels[i]);
}
}
Your code in the GetValue method recreates the array of textboxes and doing so destroys the orginal content (the textboxes dynamically created InstantiateTextFields).
In this way your loop fails with Object Reference not set.
You just need to use the global variable without reinitiaizing it
public void GetValue()
{
n = Convert.ToInt16(txtInputFields.Text);
values = new double[n];
// textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
values[i] = Convert.ToDouble(textBoxes[i].Text);
}
}
There is something to be said about reading the input text and converting it to double without checks. If your user types something that cannot be converted to a double your code will crash on the Convert.ToDouble line. Use instead
double temp;
for (int i = 0; i < n; i++)
{
if(double.TryParse(textBoxes[i].Text, out temp)
values[i] = temp;
else
{
// Not a double value....
// A message to your user ?
// fill the array with 0 ?
// Your choice....
}
}
values[n] = Convert.toDouble(textBoxes[n].Text); gives you error because n is outside of the array. You allocate an array with the size of n which is zero indexed aka the last element is at position n-1.
for (int i = 0; i < n; i++)
{
values[i] = Convert.toDouble(textBoxes[i].Text);
}

C# insertion sort after each value

How can I run the Insertion Sort code after each time user enters a value. Please notice that I don't have much knowledge about programming so showing an example or ready to use code would be appreciated.
Console.Write("How long the Insertion sort list should be?: ");
var countString = Console.ReadLine();
int count = Convert.ToInt32(countString);
int[] data = new int[count];
for (int i = 0; i < count; i++)
{
var input = Console.ReadLine();
data[i] = Convert.ToInt32(input);
Console.WriteLine(input); // << HERE THE SORTING SHOULD HAPPEN AFTER EACH VALUE THAT I ADD.
}
int j = 0;
int help = 0;
for (int i = 1; i < data.Length; i++)
{
j = i;
help = data[i];
while (j > 0 && help < data[j - 1])
{
data[j] = data[j - 1];
j--;
}
data[j] = help;
}
foreach (var i in data)
{
Console.Write("{0}, ", i);
}
}
You can visually divide your code into two parts. The first part is for inserting the values. The second part sorts these values. So you have to cut the second part and insert at the place, where sorting should happen, I hope you will find this place ;)
Also think that you should replace i in the second for with something else, for example with k
Good luck

Checking the size of a list of arrays

I have a list of string arrays:
List<string[]> parsedRaw = new List<string[]>();
This list contains lines read in from a CSV, where parsedRaw[3][5] would be the fifth item read off the third line of the CSV.
I know that I can find the number of rows in the list with:
parsedRaw.Count
But, given a row, how can I find the number of elements in that row? I'm trying to implement a test before entering a loop to read from the list, in order to avoid an "Index was outside the bounds of the array" error, where the loop is:
for (k = 0; k < nBytes; k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
I'm encountering the error on a row in the CSV that has fewer elements than the others. Before entering this loop, I need to check whether parsedRaw[i] has at least "StartInt + nBytes" elements.
Thanks for any suggestions!
A row is just a string array string[], so you can find its size using the Length property of the array.
foreach (string[] row in parsedRaw) {
for (int i = 0 ; i != row.Length ; i++) {
// do something with row[i]
}
}
The number of elements in a given row is determined by
parsedRaw[theRowIndex].Length
To fix your for loop you need to constrain the StartInt + k value to be less than the minimum of nBytes and the row length
for (k = 0; (k < nBytes) && (k + StartInt < parsedRaw[i].Length); k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
Try
List<string[]> parsedRaw = new List<string[]>();
parsedRaw.Add(new string[] {"test1", "test2"});
parsedRaw.Add(new string[] { "test1", "test2", "test3" });
int totalSize = 0;
for (int i = 0; i < parsedRaw.Count(); i++)
{
int rowSize = 0;
for (int k = 0; k < parsedRaw[i].Count(); k++)
{
rowSize += parsedRaw[i][k].Length;
}
totalSize += rowSize;
}

Categories

Resources