Search and remove item from listbox - c#

Is there a way to remove an item from a listbox based on a string?
I have been playing around for a few minutes and here is what i have so far but its not working
foreach(string file in LB_upload.Items)
{
ftp.Upload(file);
int x = LB_upload.Items.IndexOf(file);
LB_upload.Items.RemoveAt(x);
}
I could just loop through each item but I wanted to do something a little more elegant

while(LB_upload.Items.Count > 0)
{
ftp.Upload(LB_upload.Items[0].ToString());
LB_upload.Items.RemoveAt(0);
}

Based on your example, I'd do something like;
foreach(string file in LB_upload.Items)
{
ftp.Upload(file);
}
LB_upload.Items.Clear();
The problem you are probably encountering is that you are altering the list while iterating over this. This is a big no-no, and has been covered ad-nauseum on this site.

Based on the title of your question it sounds like you don't want to remove every item, just some of them. If that's the case:
for (int i = LB_upload.Items.Count - 1; i >= 0; i--)
{
if (somecondition)
{
ftp.Upload(LB_upload.Items[i]);
LB_upload.Items.RemoveAt(i);
}
}

Related

c# Get TextSelection on AvalonEdit.TextDocument

I use the AvalonEdit.TextDocument control. Now I want to get the current text-selection/textmark from it. But the class implments no any convenient property or method.
How I can get the current text selection from AvalonEdit.TextDocument?
PS: It does not really make much sense here to add some code from my app
The easiest way I found to deal with selections with an AvalonEdit editor is as follows:
IEnumerable<SelectionSegment> selectionSegments = Editor.TextArea.Selection.Segments;
TextDocument document = Editor.TextArea.Document;
foreach (SelectionSegment segment in selectionSegments)
{
//DO WHAT YOU WANT WITH THE SELECTIONS
int lineStart = document.GetLineByOffset(segment.StartOffset).LineNumber;
int lineEnd = document.GetLineByOffset(segment.EndOffset).LineNumber;
for (int i = lineStart; i <= lineEnd; i++)
{
//Do something with each line in the selection segment
}
}
In my case I needed to mark something on each line selected, so that's why I split it into lines.

C# Call an object from concatenated text

I was trying to call multiple labels with multiple names from a for loop, but the thing is that i dont want to use the "foreach" to loop trough all the controls.
I want to make a direct reference to it, for example :
for(ai = 2; ai < 11 ; ai ++)
{
this.Controls("label" + ai).Text = "SomeRandomText";
}
How can i do this?
I already tried to find this question on the net, but all i find are answers with "foreach" loops.
Thanks!!
Assuming that your labels are named "lable2" through "label10", then you can do it like this:
for(int ai = 2; ai < 11 ; ai++)
{
this.Controls["label" + ai].Text = "SomeRandomText";
}
Here is a solution that is not dependent on the control's name so you are free to change the name of the label at any point in time without breaking your code.
foreach (var control in this.Controls)
{
if (control is Label)
{
int index;
if (control.Tag != null && int.TryParse(control.Tag.ToString(), out index) && index >= 2 && index < 11)
{
((Label)control).Text = "SomeRandomText";
}
}
}
Then, all you need to do is assign a value between 2 and 11 to each control's Tag property that you want updated. You can set this property through code or set the property in the designer.
You are also free to change the values of the Tag property as you see fit. Just make sure the index checks in the code line up with the tag values you choose!

Change text of a listview

I have a quick question about listView's and how check if a ListView (which contains null items) has a certain string?
Here is the code which add to sepcific items (under column 5 in the listView). It basically checks if that item appears in Google search or not. If it does, it'll write yes to that specific row, if not it'll leave it blank:
string google2 = http.get("https://www.google.com/search?q=" + textBox1.Text + "");
string[] embedid = getBetweenAll(vid, "type='text/html' href='http://www.youtube.com/watch?v=", "&feature=youtube_gdata'/>");
for (int i = 0; i < embedid.Length; i++)
{
if (google2.Contains(embedid[i]))
{
listView1.Items[i].SubItems.Add("Yes");
}
}
Now what I am trying to do is check if that certain column contains items that say Yes. If it does color them Green if not don't.
Here's the code for that:
if (i.SubItems[5].Text.Contains("Yes"))
{
labelContainsVideo.ForeColor = System.Drawing.Color.Green;
}
My issue is I keep getting an error that says InvalidArgument=Value of '5' is not valid for 'index'.
My hunch is that there are null items in column 5 which might be messing it up but I dont know.
Any idea on how to fix this?
Check the Item to see if the SubItem Collection has the correct Number of values.
i.e.
int threshold = 5;
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems.Count > threshold)
{
if (item.SubItems[5].Text.Contains("Yes"))
{
// Do your work here
}
}
}

Append int to end of string or textbox name in a For Loop C#

I have a C# application in which there are several textboxes with the same name except for a number on the end which starts at 1 and goes to 19. I was hoping to use a for loop to dynamically add values to these text boxes by using an arraylist. There will be situations where there will not be 19 items in the arrayList so some text boxes will be unfilled. Here is my sample code for what I am trying to do. Is this possible to do?
for (int count = 0; count < dogList.Count; count++)
{
regUKCNumTextBox[count+1].Text=(dogList[count].Attributes["id"].Value.ToString());
}
So you've got a collection of text boxes that are to be filled out top-to-bottom? Then yes, a collection of TextBox seems appropriate.
If you stick your TextBox references in an array or a List<TextBox> -- I wouldn't use an ArrayList as it's considered deprecated in favor of List<T> -- then yes, you can do that:
TextBox[] regUKCNumTextBox = new []
{
yourTextBoxA,
yourTextBoxB,
...
};
Then yes your logic is possible, you can also query the control by it's name, though that would be heavier at runtime - so it's a tradeoff. Yes, in this solution you must set up a collection to hold your text box references, but it will be more performant.
Try this:
(By the way I am assuming you use WinForms)
for (int count = 0; count < dogList.Count; count++)
{
object foundTextBox = this.Controls.Find("nameofTextBoxes" + [count+1]);
if (foundTextBox != null)
{
if (foundTextBox is TextBox)
{
((TextBox)foundTextBox).Text=(dogList[count].Attributes["id"].Value.ToString());
}
}
}
With this code you are trying to find a Control form your Forms Controls collection. Then you have to make sure the control is of the TextBox type. When it is; cast it to a TextBox and do what you want with it. In this case; assign a value to the Text property.
It would be more efficient to keep a collection of your TextBoxes like in the solution offered by James Michael Hare
Yikes; something doesn't seem quite right with the overall design there; but looking past that, here's a quick stab at some pseudo code that might work:
for (int count = 0; count < dogList.Count; count++)
{
var stringName = string.Format("myTextBoxName{0}", count);
var ctrl = FindControl(stringName);
if(ctrl == null) continue;
ctrl.Text = dogList[count];
}

Find "not the same" elements in two arrays

I have two integer lists (List<int>). They contain the same elements, but List 1 contains elements that are not in the List 2.
How to find which elements of the List 1 ARE NOT in the List 2.
Thanks :)
PS. lang is c#
You can use IEnumerable.Except:
list1.Except(list2);
new HashSet<int>(l1).ExceptWith(l2);
A very easy solution:
HashSet<int> theSet1 = new HashSet<int>(List1);
theSet1.ExceptWith(List2);
For simplicity you can use the Contains method and check for one list not containing an element of the other:
for (int i = 0; i < list2.Count; ++i)
{
if (!list1.Contains(list2[i]) //current element is not in list 1
//some code
}
If your solution is that firs list contain second and to you hunting onli records added after first list ,
Maybe this is going to be useful
public static int DokleSuIsti(IList<string> prevzemNow, IList<string> prevzemOld)
{
int dobroja = 0;
int kolikohinaje;
if (prevzemOld.Count() < prevzemNow.Count())
{
kolikohinaje = prevzemOld.Count();
}
else
{
kolikohinaje = prevzemNow.Count();
}
for (int i = 0; i < kolikohinaje; i++)
{
if (!Object.Equals(prevzemNow[i], prevzemOld[i]))
{
dobroja = i;
return dobroja;
}
dobroja = i;
}
return dobroja;
}
After that you can use that int as starting point for walk trough your Ilist
If they are not sorted or something, you are going to have a hard time.
Either O(N^2) algorithm (a simple, stupid loop) or additional data structures, tell me which do you prefer.
Or, you can of course alter the source data by sorting, which I suppose is not an option.

Categories