I want to delete some parts (string or int values) for selected listbox item in C#.
As shown on picture I get some random coordinates on picturebox which is shown on Listbox1. Then I selected randomly these points to add Listbox2 by ADD button. I want make new arrangement at Listbox2 which means it should be 1.selected point 2.3.4.selected points ..(not randomly 3.rd 6.th 7.th ..)
Secondly I want to transfer to coordinate (just numbers) to Listbox3. How can I do?
(source: hizliresim.com)
To add selected coordinate
private void add()
{
int c = listBox1.Items.Count - 1;
for (int i = c; i >= 0; i--)
{
if (listBox1.GetSelected(i))
{
int a = listBox2.Items.Count + 1;
listBox2.Items.Add(a+" "+listBox1.Items[i]);
// listBox1.Items.RemoveAt(i);
}
}
}
The question is not really clear but i will try to give you an answer as good as i understood the question. So from what i got you would like to make it so the numbers are "1 ,2 ,3 ..." in ListBox2 instead of random once and also you would like the same result but only the numbers in ListBox3.
Hope this help at least this is what i understood you are trying to do. Btw all this is assuming that all your data is based on the example you provided!
//We are going to read the string from the first box and find the first
//occurence of "." and get the rest of the string after that we are going to add it to ListBox2
string for_lisbox2 = listBox1.Items[i].ToString();
for_lisbox2 = for_lisbox2.Substring(for_lisbox2.IndexOf('.'));
int current_index = listBox2.Items.Count + 1;
listBox2.Items.Add(current_index + for_lisbox2);
//Then we do something similar but this time we are finding last empty space " " so we can find the start of the second coordinates and we mark it as Y
//then we do the same with X and finaly we add them to Lisbox3
string for_listbox3 = for_lisbox2;
//finding second set of coordinates by finding the last occurence of ' ' and using the result for a start index of Substring method this will return the second number
string Y = for_listbox3.Substring(for_listbox3.LastIndexOf(' '));
// this is just to remove the numbers that we just got in the previous line so they are not in your way for the next operation
for_listbox3 = for_listbox3.Substring(0, for_listbox3.LastIndexOf(' '));
//this is just like geting the other number
string X = for_listbox3.Substring(for_listbox3.LastIndexOf(' '));
for_listbox3 = X + " " + Y;//displaying the results in ListBox3 as "72 134"
listBox3.Items.Add(for_listbox3);
.
Related
I am playing with C#. I try to write program that frames the quote entered by a user in a square of chars. So, the problem is... a user needs to indicate the number of lines before entering a quote. I want to remove this moment, so the user just enters lines of their phrase (each line is a new element in the string array, so I guess a program should kinda declare it by itself?..). I hope I explained clear what I meant x).
I've attached the program code below. I know that it is not perfect (for example, when entering the number of lines, I use the conversion to an integer, and if a user enters a letter, then this may confuse my electronic friend, this is a temporary solution, since I do not want to ask this x) The program itself must count these lines! x)) Though, I don't understand why the symbols on the left side are displayed incorrectly when the program displays output, but I think this also does not matter yet).
//Greet a user, asking for the number of lines.
Console.WriteLine("Greetings! I can put any phrase into beautiful #-square."
+ "\n" + "Wanna try? How many lines in the quote: ");
int numberOfLines = Convert.ToInt32(Console.ReadLine());
//Asking for each line.
string[] lines = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
Console.WriteLine("Enter the line: ");
lines[i] = Console.ReadLine();
}
//Looking for the biggest line
int length = 0;
for (int i = 0; i < numberOfLines; i++)
{
if (length < lines[i].Length) length = lines[i].Length;
}
//Starting framing
char doggy = '#';
char space = ' ';
length += 4;
string frame = new String(doggy, length);
Console.WriteLine(frame);
for (int i = 0; i < numberOfLines; i++)
{
string result = new string(space, length - 3 - lines[i].Length);
Console.WriteLine(doggy + space + lines[i] + result + doggy);
}
Console.WriteLine(frame);
Console.ReadLine();
}
}
}
There is performance gap and functionality between "Generic Lists" and arrays, you can read more about cons and pros of this two objects in the internet,
for example you can use list as Dai mentioned in comment like this
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
or you can use arraylist
ArrayList arraylist = new ArrayList();
arraylist.Add();
or even you can change the size of array any times but it erase data in it
int[] arr = new int[100];
there is a function called ToArray() you can use it to change generic list to array
Your problem of the left side output is, that you add two values of char. This is not what you expect to be. You must convert the char to a string to append it to other strings:
Console.WriteLine(doggy.ToString() + space.ToString() + lines[i] + result + doggy.ToString());
I'm trying to find the next occurrence of a string in a list that is created dynamically. First I create the list with buttons that save text to a txt file and then divide the file with "," in to a list and by clicking items in the list, I update a textview item next to the list.
The var it = lstv.GetItemAtPosition(e.Position); gives the position on where to start searching for the next string. The next string is one of two possibilities.
List creation
string content;
using (var streamReader = new StreamReader(filename))
{
content = streamReader.ReadToEnd();
}
content = content.TrimEnd(',');
char[] delimiterChars = { ',' };
data = content.Split(delimiterChars);
var myAdapter = new ArrayAdapter(this, Resource.Layout.TextViewItem, data);
lstv.Adapter = myAdapter;
The suggestions I have found only get the first or last occurrence, but I have multiple occurrences of the values and I need to get next occurrence from the clicked position
Edit:
Should have mentioned there are X number of items between the the starting position and the string I would want get.
Edit2:
The list is something like this:
String 1 or String 2
String x
String x
String x
String x
String 1 or String 2
String x
String X
String 1 or String 2
The amount of String x between the next String 1 or 2 I want to get varies. When the user clicks on String 1/2 the program needs to find the next position where the value is String 1 or String 2.
Oh yes it gives an item. And when I get the next required string I can get position of that item and what I need to do next. Sorry if I'm a bit too unclear.
Edit3:
OnListItemClick method
protected void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
var it = lstv.GetItemAtPosition(e.Position);
View v = (sender as View);
int pos = lstv.GetPositionForView(v);
if (it.ToString().Equals("String1") || it.ToString().Equals("String2")
{
/*while (!it.ToString().Equals("String1") || !it.ToString().Equals("String2"))
{
it = lstv.GetItemAtPosition(e.Position + 1);
lstv.GetItemAtPosition(e.Position);
//lstv.SetSelection(e.Position);
}*/
//it = lstv.GetItemAtPosition(e.Position - 1);
int itt = lstv.SelectedItemPosition;
txtv.Text = it.ToString();
txtv2.Text = pos.ToString();
txtv3.Text = itt.ToString();
}
else
{
// Some code here
}
}
I try to get the position with View v = (sender as View); but it always returns the position as -1 no matter what item I click in the list.
In the list if I click for example a second occurrence of String 1 the program should find the next item that is either String 1 or String 2. When found, that should give position of the item.
The while loop works if I only search for String 1 or 2 but not if I search for both. I'm probably doing a lot of things wrong, but if I could get a little help on what look for I would be grateful.
A while loop should solve the issue...
The while loop works if I only search for String 1 or 2 but not if I search for both.
Remember : !(a || b) is the same as (!a && !b)
Therefore you should write:
while (!it.ToString().Equals("String1") && !it.ToString().Equals("String2")) {
Would it be :
return lstv.GetItemAtPosition(e.Position++);
?
I've made a program that extracts some info from a file , do some operations with it and store it back on a list.
Following this link:
Are 2 dimensional Lists possible in c#?
I've been able to create a class with a list who would suit my needs. But after some debugging i've found that i was overwriting the list on each loop iteration.
Then i decided to make an array of lists - followed this link:
How to create an array of List<int> in C#?
Created an array of lists, initialized it and added elements. But when it needs to move to the next list position , it throws the out of boundaries exception.
I've tried a few things (readed about race condition) but none of 'em worked.
The problem will happen only when i open more than one file with my code ; otherwise it works perfectly.
Exception is thrown at xmldata , in the last iteration of the current file.
Ex: Selected two files, each one will add five elements. In the last element of the first file the exception will be thrown and there's data in the last element's position to be added.
Additional information: Index was outside the bounds of the array. (Exception thrown).
Any help will be appreciated. Thanks a lot.
Code:
List<xmldata>[] finalcontent = new List<xmldata>[9999];
finalcontent[listpos] = new List<xmldata>();//Initializing a list for each filename
foreach (Match m in matches)
{
Double[] numbers;
string aux;
aux = m.Groups[1].ToString();
aux = Regex.Replace(aux, #"\s+", "|");
string[] numbers_str = aux.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
numbers = new Double[numbers_str.Length];
for (int j = 0; j < numbers.Length; j++)
{
numbers[j] = Double.Parse(numbers_str[j], CultureInfo.InvariantCulture);
//Converts each number on the string to a Double number, store it in a position
//in the Double array
numbers[j] = numbers[j] / 100; //Needed calculus
numbers[j] = Math.Round(numbers[j], 3); //Storing numbers rounded
}
string values = String.Join(" ", numbers.Select(f => f.ToString()));
if (i <= colors_str.Length)
{
finalcontent[listpos].Add(new xmldata//The exception is thrown right here
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
}//Closing if
i++;
}//Closing foreach loop
Link to the file: https://drive.google.com/file/d/0BwU9_GrFRYrTT0ZTS2dRMUhIWms/view?usp=sharing
Arrays are fixed size, but Lists automatically resize as new items are added.
So instead, and since you're using Lists anyway, why not use a list of lists?
List<List<int>> ListOfListsOfInt = new List<List<int>>();
Then, if you really absolutely must have an array, then you can get one like this:
ListOfListsOfString.ToArray();
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
This is a big example, but check this one. You increase 'jx' before entering the statement, possibly exceeding the boundary of cnt?
Try changing the following:
if (i <= colors_str.Length)
to
if (i < colors_str.Length).
In fact I'm convinced that this is the problem.
This is because refereces begin at 0 and the last reference is length - 1, not length.
When using a list - it is better to use native functions for it.
List<xmldata>[] finalcontent = new List<xmldata>();
......
finalcontent[listpos] = new List<xmldata>(); insted of var _tmpVariable = new List<xmldata>();//Initializing a list for each filename
......
_tmpVariable.Add(new xmldata
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
fs.Close();//closing current file
listpos++;//Increment list position counter
finalcontent.Add(_tmpVariable); // add list into list
As there is no exception details it is hard to get where the exception is thrown.
It could be a list issue, a string issue or other (even file reading issue as well),
So please update this with current exception details.
I have a multi-line textbox of sequences, which the game will play one after the other. For example, the textbox may contain this:
RGBY
YGBR
RGBB
I understand that to read the first line of a multi-line textbox, I must write this:
First sequence:
textBox1.Lines[0].Length //Reads first line only for sequence 1
But how can I make it read the next line in a general sense? n+1 where n is the previous line.
New sequence:
textBox1.Lines[0 + 1].Length //Go to next line for future sequences
Any help is appreciated. Thank you in advance!
You need to store the current index in a variable, a field or property in your class.
private int CurrentIndex { get; set; }
Now you can iterate all lines, for example in a button-click event handler where you want to advance to the next line until end:
if (CurrentIndex + 1 < textBox1.Lines.Length)
{
string currentLine = textBox1.Lines[++CurrentIndex];
}
for(int i=0; i < textBox1.Lines.Count(); i++)
{
var currentLine = textBox1.Lines[i];
// do what you want with current line
}
I have a list that contains file names like f1, f2, f3,...,f6. my
program needs to output a list with file names appearing in
random order such as f4,f1,f6,f2,f3,f5.
I want to swap or shift string correctly inside a list I have a list of
size 6 named fileName already containing 6 different file names I
am swapping file names inside of a list fileName as follows and fil
is also a string for remembering current string or file name.
temp =-1;
foreach (Control control in tableLayoutPanel1.Controls) // run loop untill every control inside tablelayoutpanel1.Controls is check or read
{
Button btns = control as Button; // btn sotre the
current button in table.contr
if (btns != null) // check btn got a button from
the panel then
{
temp++;
int randomNumber = 0;
randomNumber = theArray[temp]; //this pic the random number from 0 index then 1 so on theArray already contains random number from 0 to 5 without any repitition and also tested
fil = fileName[randomNumber]; //fil for holding string
fileName[temp] = fileName[randomNumber]; // at filname[0]
swap or shift filename[randomNumber] random are between 0 to
5 and without repitition
fileName[randomNumber] = fil; // this line isnt even necessary
but to be safe i wrot
btns.BackgroundImage = images[randomNumber]; // change
btn image to current random image
copyImages.Add(images[randomNumber]);
btns.BackgroundImage = null; // i purposely doing this :)
}
Using that code I am able to swap string but I cant swap them
correctly as it only run for 6 times so it should swap 6 strings
(each with different name) inside the list on 6 different location
inside the list fileName but its not happening some strings are
showing twice or thrice, hoping someone can point out what I am
doing wrong and theres no index out of range or exception error
I tested it for like hundred time please help thanks and any idea
suggestion or piece of code will be helpful and fil just storing the string at the location of fileName[temp] :) and temp just going from 0 to 5 in a loop
i dont want to shuffle them i just want to swap them according to given index which i am doing in my code but cant to it properly theArray already contains the suffle index i just want to assign the fileName[0] index to theArray[temp] i can send you my proj if you want to have a look just send me hi to my id which show in my profile
So given you have a List of length 6 and an int[6] containing 0 to five in random order
List<String> newList = newList<String>();
foreach(int position in theArray)
{
newList.Add(filename[pos]);
}
filename.Clear();
fileName.AddRange(newList);
would be one way.
or you could simply do filename = newList and not bother with the Clear and AddRange.
You stored the wrong String in your temporary variable.
fil = fileName[temp]; // index changed here
fileName[temp] = fileName[randomNumber];
fileName[randomNumber] = fil;
This is a simple way to shuffle elements in an array. Basicly you go through the array from one end to the middle, swapping each element with one selected at random. Since each swap operation results in two elements being randomly placed, when we reach the middle, the whole array is shuffled.
void Main()
{
var arr = new string[] {"a","b","c"};
Shuffle(arr);
// arr is now shuffled
}
public static void Shuffle<T>(T[] arr)
{
Random r = new Random();
for(int i = arr.Length; i > arr.Length / 2; i--)
{
Swap(arr, r.Next(i), i -1);
}
}
private static void Swap<T>(T[] arr, int first, int second)
{
T temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}