how i can empty listbox contents c#? - c#

i have this code:
public void LoadData1(String link)
{
string temp="";
int pos = 0;
for (int x = 0, y = 0; x < link.Length; x++) //separate various code
if (link[x] == 'y')
{
for (temp = ""; y < x; y++)
if(link[y]!='y')
temp += link[y];
list[pos] = temp;
pos++;
y = x++;
}
string nota=list[0];
for (int a = 0; a < list.Count() && list[a]!=null ; a++,nota=list[a])
{
string tempI = "";
//immagine
for (int x = 0; x < nota.Count(); x++)
{
if (nota[x] == 'p')
tempI += '+';
else
tempI += nota[x];
}
//nome della pagina
string temp1 = "";
int c = tempI.Count();
if (tempI.Count() > 2)
if (tempI.ElementAt(2) == 'l') //sol
{
for (int x = 0; x < c; x++)
if (x == 3 && tempI.ElementAt(3) == 'd')
temp1 += '#';
else
temp1 += tempI.ElementAt(x);
}
else
{
for (int x = 0; x < c; x++)
if (x == 2 && tempI.ElementAt(2) == 'd')
temp1 += '#';
else
temp1 += tempI.ElementAt(x);
}
else
temp1 = tempI;
this.Temp.Add(new ImageText() { Text = temp1, linkImage = "/Accordi/"+tempI+".png" });
}
this.IsDataLoaded1 = true;
this.Temp = new ObservableCollection<ImageText>();
}
this fill a listbox composed of text and image. but i have this problem: when i fill the listbox with 3 element(for example) it's go all right, but when i call again the function for fill the listbox with 2 element, the listbox show the two element of call and at the third space show the element of my previous call!! how i can solve this problem?
the listbox is binding by temp, and the string link contains a sequence of code like "DoyDodyRey"

You're setting the 'nth' element each time you load data, but you're doing nothing about what's already there, so if you had a third element on a previous call, and only two on a subsequent one, the third one will still be there.
It's simply a matter of clearing it first, or removing excess items afterwards. It's difficult to see from your code exactly what's going on, but I think a call to list.Clear() right at the top of the method will probably do the job.
If you want to simply remove excess items, I think you should be able to add while (list.Count() >= pos) list.Remove(pos); right after your first for loop.

cant you declare the list at the begining so its empty
List<string> yourlist = new List<string>();
and you dont need to use pos in lists you can just use
yourlist.add(temp)
first post in the list gets yourlist[0] and so on
hope this helps a little :)

Related

Extract strings from a textbox to a listbox

{
int numlines = txtbox.Lines.Count();
string[] l = txtbox.Lines;
for (int i = 0; i <= numlines; i++)
{
string lona = l[i].Substring(25, 12);
lstbox.Items.Add(lona);
}
}
Hi, I want to move some elements from a textbox to a listbox using a for loop and a substring method. This is the code i tryed and it causes an exception while running it in a loop.
Since C# collections are zero based, correct for loop uses < Count, not <= Count condintion:
for (int i = 0; i < numlines; i++) // i < numlines, not i <= numlines
{
...
}
Let's simplify the routine and get rid of for loop: we add each line which is long enough (so we'll be able to get a Substring):
foreach (string line in txtbox.Lines) {
if (line.Length >= 25 + 12)
lstbox.Items.Add(line.Substring(25, 12));
}

Increment variable after third time something else happened

Excuse me for the silly question, but i can't manage to solve it.
How can i make something to happen every third time ?
Times(left number):
shipmentId=0
shipmentId=0
shipmentId=1
shipmentId=1
shipmentId=2
shipmentId=2 ....
int occurrence = 0;
int counter = 0;
foreach (var el in elmOrderData)
{
if (el.Name == "shipmentIndex")
{// we are entering here for every element that his name is "shipmentIndex"
el.SetValue(shipmentId);
secondTime++;
}
if ((secondTime % 2) == 0)
{// every third time we see "shipmentIndex"
secondTime = 1;
shipmentId++;
}
}
You could use a bool as in the following example. This will display messageboxes 1,3,5,7 and 9:
bool test = false;
for (int i = 0; i < 10; i++)
{
if (test)
MessageBox.Show(i.ToString());
test = !test;
}
Trying to piece together your notes - whether 'it' happens every time or not. How about this?
int occurrence = 0;
int counter = 0;
foreach(var a in list)
{
if(some_condition)
{
// do something..
occurrence++
if(occurrence % 2 == 0)
{
counter++
}
}
}
Why not just increment everytime and just divide by 2?
for(var i = 0; i<20; i++)
{
var j = i / 2; // or bit shift
//do work on j instead of i
}

indexOutofRange BubbleSort when using inputbox

Its been bugging me for hours because it is always returning 0 at numbers[i] and I cant figure out the problem. code worked for a different program but I had to change it so it could have a custom array size and that's when everything went wrong.
any help would be great.
Thanks in advance.
int[] numbers = new int[Convert.ToInt16(TxtArray.Text)];
int j = 0;
for (j = numbers.Length; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 1; i++)
{
string NumbersInput = Microsoft.VisualBasic.Interaction.InputBox("Enter Numbers to be sorted",
"Numbers Input", "", -1, -1);
numbers[i] = Convert.ToInt16(NumbersInput);
//returns 0 in if statement
if (numbers[i] < numbers[i + 1])
{
int intTemp = 0;
intTemp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = intTemp;
}
}
}
for (int i = 0; i < numbers.Length; i++)
{
LstNumbers.Items.Add(numbers[i]);
}
private void button1_Click(object sender, EventArgs e)
{
int sizeOfArrayInt = Convert.ToInt32(arraySize.Text);
int[] array = new int[sizeOfArrayInt];
string numbers = arrayValues.Text;
string[] numbersSplit = numbers.Split(',');
int count = 0;
foreach (string character in numbersSplit)
{
int value;
bool parse = Int32.TryParse(character, out value);
if (value != null)
{
array[count] = value;
}
count++;
}
array = this.SortArray(array);
foreach (int item in array)
{
this.listBox.Items.Add(item);
}
}
private int[] SortArray(int[] arrayToSort)
{
//int[] sortedArray = new int[arrayToSort.Length];
int count = arrayToSort.Length;
for (int j = count; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 2; i++)
{
if (arrayToSort[i] < arrayToSort[i + 1])
{
int intTemp = 0;
intTemp = arrayToSort[i];
arrayToSort[i] = arrayToSort[i + 1];
arrayToSort[i + 1] = intTemp;
}
}
}
return arrayToSort;
}
strong text
This I got to work as a Windows Form and the output displays in the list box as each array item or individual i iteration over the array. Of course there is no error checking. Hope that helps.
Setting aside the strangeness of how you are working with text boxes, your problem with throwing an exception would happen even without them because it lies here, in your inner loop:
for (i = 0; i <= j - 1; i++)
Suppose that numbers.Length == 2. This means that j == 2. So on the first time through the outer loop, you hit the inner loop with these conditions. The first time through, i == 0. You get to the if statement:
if (numbers[i] < numbers[i + 1])
numbers[0] exists, and numbers[1] exists, so this iteration goes through fine and i is incremented.
Now i == 1. Now the loop checks its boundary condition. i <= j - 1 == true, so the loop continues. Now when you hit that if statement, it tries to access numbers[i + 1], i.e., numbers[2], which does not exist, throwing an IndexOutOfRangeException.
Edit: Came back and realized that I left out the solution (to the exception, anyway). For the bubble sort to work, your inner loop's boundary condition should be i <= j - 2, because j's initial value is == numbers.Length, which is not zero-based, while array indexes are.
Second Edit: Note that just using a List won't actually solve this problem. You have to use the right boundary condition. Trying to access list[list.Count()] will throw an ArgumentOutOfRangeException. Just because a List will dynamically resize doesn't mean that it will somehow let you access items that don't exist. You should always take time to check your boundary conditions, no matter what data structure you use.

combine adjacent parallel lines

There is an image which only has vertical lines and horizontal lines. But there are some lines that are the same or they are close to each other, but they should be combined to only one line. Also I wrote loop to add line in a new list, the speed is slow. So I wonder if there are some efficient way for me to combine these adjacent lines to one line.
The following is the code:
for (int i = 0; i < RecoverLine_list.Count; i++) {
for (int j = 0; j < RecoverLine_list.Count; j++) {
for (int m = 0; m < RecoverLine_list.Count; m++) {
if (RecoverLine_list[i] != RecoverLine_list[j]
&& RecoverLine_list[i] != RecoverLine_list[m]
&& RecoverLine_list[j] != RecoverLine_list[m]) {
if (RecoverLine_list[i].orientation == 0
&& RecoverLine_list[j].orientation == 0
&& RecoverLine_list[m].orientation == 0) {
if (Math.Abs(RecoverLine_list[i].P1.Y - RecoverLine_list[j].P1.Y) < 3
&& Math.Abs(RecoverLine_list[i].P1.Y - RecoverLine_list[m].P1.Y) < 3
&& Math.Abs(RecoverLine_list[j].P1.Y - RecoverLine_list[m].P1.Y) < 3) {
// define RecoverLine_list[i] as grid line
GridLine_list.Add(RecoverLine_list[i]);
}
}
}
}
}
}
(REWRITTEN) So, assuming you want to somehow filter horizontal and vertical lines which are 'similar' and want both the code and good condition for what 'similar' should be, then here are my thoughts:
First split horizontal and vertical lines:
List<Line> vert = new List<Line>();
List<Line> horiz = new List<Line>();
foreach(Line ln in RecoverLine_list)
if(ln.orientation == 0) horiz.Add(ln);
else vert.Add(ln);
horiz.Sort(x, y => x.P1.Y.CompareTo(y.P1.Y));
vert.Sort(x, y => x.P1.X.CompareTo(y.P1.X));
or something like that (not exactly sure what your orientation is, I am just guessing including the coding of sorting using lambdas).
Then you can search the lines in one pass extracting good-ones:
List<Line> filtered = new List<Line>();
for(int i = 0; i < horiz.Count; i++) {
filtered.Add(ln); // always add, we can skip next:
if(i+1 >= horiz.Count) break;
if(Math.Abs(horiz[i].P1.Y - horiz[i+1].P1.Y) <= 3)
&& Math.Abs(horiz[i].P1.X - horiz[i+1].P1.X) <= 3)
&& Math.Abs(horiz[i].P2.X - horiz[i+1].P2.X) <= 3))
i++; // skip this line for being similar
}
but that is not final solution, because we can have lines close to each other in one coordinate but not in the other. So we need to add inner loop:
for(int i = 0; i < horiz.Count-1; i++) {
for(int j = i+1; j < horiz.Count; j++) {
if((horiz[j].P1.Y - horiz[i].P1.Y) > 3)
break; // this one is too far, all next will be
if(Math.Abs(horiz[i].P1.Y - horiz[j].P1.Y) <= 3)
&& Math.Abs(horiz[i].P1.X - horiz[j].P1.X) <= 3)
&& Math.Abs(horiz[i].P2.X - horiz[j].P2.X) <= 3))
horiz.RemoveAt(j--); // skip this line for being similar
}}
Got the idea? Same for vertical lines.

Browse a matrix

I want to browse a matrix like these one :
I want browse the first row, get the smallest number, then browse the row matching with the precedent smallest number.
Ex : I browse the A row : I browse the cell A,A , I get 0. I don't keep it (because it's 0) I browse the cell A,D I get 5. I keep it. I browse the cell A,G I get 8 but i don't keep it because it is superior to 5. I browse cell A,K and I get 4 I keep it (< 5).
For the moment it's ok, a simple loop is sufficient to do this. Then I want to browse the row K and if possible don't browse the cell K,A because I already browsed it when I browsed the row A.
You need to loop through an upper/lower half of the matrix? I assume a matrix is an array of int arrays.
var matrix = new int[][]{ ... };
int smallest = 0;
for(int i = 0; i < matrix.Length; i++)
{
for(int j = 0; j < matrix.Length; j++)
{
int number = matrix[i][j];
if (number != 0 && number < smallest)
smallest = number;
}
}
Although, I didn't quite get
then browse the row matching with the precedent smallest number
part.
Here the solution I found :
private static IEnumerable<int> ComputeMatrix(int[,] matrix)
{
// check args
if (matrix.Rank != 2) { throw new ArgumentException("matrix should have a rank of 2"); }
if (matrix.GetUpperBound(0) != matrix.GetUpperBound(1)) { throw new ArgumentException("matrix should have the same size");}
// indice treated
List<int> treatedIndex = new List<int>();
for (int i = 0; i <= matrix.GetUpperBound(0); i++)
{
if (treatedIndex.Count == matrix.GetUpperBound(0))
break;
// distance minimum between 2 points
int distanceMin = Int32.MaxValue;
// next iteration of index
int nextI = i;
// add the index to ignore in the next iteration
int nextJ = -1;
for (int j = 0; j <= matrix.GetUpperBound(1); j++)
{
if (treatedIndex.IndexOf(j) == -1)
{
if (matrix[i, j] != 0 && matrix[i, j] < distanceMin)
{
distanceMin = matrix[i, j];
nextI = j;
nextJ = i;
}
}
}
i = nextI - 1;
treatedIndex.Add(nextJ);
yield return distanceMin;
}
}

Categories

Resources