C# Get Separate ListBox Items as strings - c#

I'm a little bit confused on something. I wrote a code that will count the number of items in a ListBox and then write them into each cell of an excel file. Like this:
int test = ItemsList.Items.Count;
for (int i = 1; i < test; i++)
{
foreach (string itemText in ItemsList.Items)
{
worksheet.Cells[i, 0] = new Cell(itemText);
}
}
for (int i = test + 1; i < 100; i++)
{
worksheet.Cells[i, 0] = new Cell("");
}
This writes the code into excel properly however instead of displaying each item in the listbox separately it only displays the very last item in all of the cells. Any thoughts on how I can get each item from the list as a separate string for each cell?

You don't need to use 2 loops. Do something like:
for (int i = 1; i <= test; i++)
{
worksheet.Cells[i, 0] = new Cell(ItemsList.Items[i-1]);
}

You can use string.Join(string separator, IEnumerable values)
More details: http://www.dotnetperls.com/string-join http://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx

Related

Summarize all numbers of a column in Listview

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;
}
}
}

Populating a listbox in c#

I have a listbox and I manage to bind the Excel worksheet to the list box (after hours of researching on the Internet).
Now I need to read the values from the sheet into the listbox, but unable to locate any suitable solution.
This is what I have done so far:-
private void LoadExcelSheet(string path, int sheet){
_Application excel = new Excel.Application();
Workbook wb;
Worksheet ws;
int row = 0;
int col = 0;
wb = excel.Workbooks.Open(path);
ws = wb.Worksheets[sheet];
for (row = 1; row < 10; row++){
for (col = 1; col < 6; col++){
listBox1.Items.Add(ws.Cells[row, col].Value2);
}
}
}
//------------------ end of LoadExcelSheet---------------------------
this only display 1 row with each item of data on top of each other eg:-
aaaaaaaa
bbbbbbbb
cccccccc
dddddddd
instead of: aaaaaaaa bbbbbbbb cccccccc dddddddd
Thanks in advance..
The issue is with your for loops, try this:
for (var row = 1; row < 10; row++)
{
string r = "";
for (var col = 1; col < 6; col++)
{
r += " " + ws.Cells[row, col].Value2;
}
listBox1.Items.Add(r.Trim());
}
You are populating the list box inside a loop containing the columns, try something like
for (row = 1; row < 10; row++){
string a = "";
for (col = 1; col < 6; col++){
a += ws.Cells[row, col].Value2+" ";
}
listBox1.Items.Add(a);
}
Let's split the problem
Data collection
Collected data representation
Data collection (with a help of Linq):
using System.Linq;
...
string[] data = Enumerable
.Range(1, 9) // 9 rows, starting from 1
.Select(row => string.Join(" ", Enumerable // cols are joined with space
.Range(1, 5) // 5 columns in each row
.Select(col => ws.Cells[row, col].Value2)))
.ToArray();
And data representation (as ListBox items):
listBox1.Items.AddRange(data);

Storing cookie in string array variable and displaying the string

I am trying to store the cookie in an array of string and splitting it .when i try to display the array i am getting index out of bound error in the for loop.
Please not the the value of "cboColumn.getSelectedValues()" is a list of selected columns from a grid which is in format"column1,column2,column3......columnn"
Response.Cookies["Column"].Value = cboColumn.getSelectedValues();
String items = Request.Cookies["Column"].Value;
String[] item = items.Split(',');
Response.Write(items);
Response.Write(item[0]);
for (int i = 0; i <= item.Length; i++)
{
Response.Write(item[i]);
}
Change your for loop like this:-
for (int i = 0; i <= item.Length - 1; i++)
{
Response.Write(item[i]);
}
Or as suggested by #BillK, you can simply change the condition like this:-
for (int i = 0; i < item.Length ; i++)
Array is zero index based so it will range from 0 to (n-1) but you are trying to fetch value from 0 to n, which is causing this issue.

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);
}

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