I have 1 listbox and 2 buttons and 2 textboxes. When i press a button my listbox shows + all my data.
In the listbox i have around 30 names. With different names in it. Some names are the same.
And when i press the other button so shall in one textbox (that i already done). Show a name that i selected in the list. But! Here comes the tricky part.
I want to have in the last textbox the name from a listbox that can calculate all names that are in the same name.
If i selected "Peter" in the list and Peter is 3-4 times in that list. How can i write it out so it displays 3 times? I mean 3 (int) times.
And here is the Code:
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
_items.Add("Per Lindmark, 2012-05-01");
// add more items
_items.Add("Elin Ivarsson, 2012-05-13");
listBox1.DataSource = _items;
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();
}
}
}
Here is one solution.
var name = txtBox1.Text.Split(' ')[0];
if (string.IsNullOrEmpty(name))
{
return;
}
var items = listBox1.DataSource as List<string>;
var count = items.Count(x => x.Split(' ')[0] == name);
textBox2.Text = count.ToString();
I hope I understood your question :)
You could iterate over all items in the list and compare the names:
int counter = 0;
foreach (string item in listBox1.Items)
{
if (item == name)
counter++;
}
Of course, you'd have to extract the name from the item in the list properly.
Related
I am adding items to the listbox using backgroundworker. It is showing all the items present in the list one by one after some interval of time. I want to show only current item in the list and not all the items.
This is what I have tried.
private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{
List<string> result = new List<string>();
var found = obj.getFiles();//List<strings>
if (found.Count != 0)
{
for (int i = 0; i < found.Count; i++)
{
int progress = (int)(((float)(i + 1) / found.Count) * 100);
if (found[i].Contains("SFTP"))
{
result.Add(found[i]);
(sender as BackgroundWorker).ReportProgress(progress, found[i]);
}
System.Threading.Thread.Sleep(500);
}
e.Result = result;
}
}
private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
listBox3.Items.Add(e.UserState);
}
I want to show only current item in the list and not all the items.
Although this is a bit of a hack, I think it should work for what you describe:
// just call clear first
listBox3.Items.Clear();
listBox3.Items.Add(e.UserState);
Truth be told, are you sure you want a ListBox in this circumstance? After all, it's not really a list, it's only an item.
I am really confused on thinking which control to use for my purpose.
I am having list of items say item1 to item10. User can select 4 or 5 items in any order.
Now user selected items has to be separated in same order.
For example, if the user selected the items in following order, item4, item8, item3 and item2.
I want it in the same order. item4,item8,item3,item2.
How do I achieve this in winforms control?
It is not a very nice solution but I wrote it as you asked.
Set the SelectionMode of your ListBox to MultiExtended or MultiSimple as you need.
Then write this code in SelectedIndexChanged event of your ListBox:
List<string> orderedSelection = new List<string>();
bool flag = true;
private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
if (flag)
{
flag = false;
var list1 = listBox3.SelectedItems.Cast<string>().ToList();
if (listBox3.SelectedItems.Count > orderedSelection.Count)
{
orderedSelection.Add(list1.Except(orderedSelection).First());
}
else if (listBox3.SelectedItems.Count < orderedSelection.Count)
{
orderedSelection.Remove(orderedSelection.Except(list1).First());
}
var list2 = listBox3.Items.Cast<string>().Except(list1).ToList();
listBox3.Items.Clear();
for (int i = 0; i < list1.Count; i++)
{
listBox3.Items.Add(list1[i]);
listBox3.SelectedIndex = i;
}
foreach (string s in list2)
{
listBox3.Items.Add(s);
}
flag = true;
}
}
When user selects an item, It comes to first of the list and the rest of the items comes next.
Also, there is an alternative way. You can use a CheckedListBox with two extra button for moving selected items up and down. So user can change the order of selected items.
This solution uses CheckListBox's ItemCheck event along with a private List to keep track of the click items order.
protected List<string> clickOrderList = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
// Populate the checked ListBox
this.checkedListBox1.Items.Add("Row1");
this.checkedListBox1.Items.Add("Row2");
this.checkedListBox1.Items.Add("Row3");
this.checkedListBox1.Items.Add("Row4");
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (sender != null && e != null)
{
// Get the checkListBox selected time and it's CheckState
CheckedListBox checkListBox = (CheckedListBox)sender;
string selectedItem = checkListBox.SelectedItem.ToString();
// If curent value was checked, then remove from list
if (e.CurrentValue == CheckState.Checked &&
clickOrderList.Contains(selectedItem))
{
clickOrderList.Remove(selectedItem);
}
// else if new value is checked, then add to list
else if (e.NewValue == CheckState.Checked &&
!clickOrderList.Contains(selectedItem))
{
clickOrderList.Insert(0, selectedItem);
}
}
}
private void ShowClickOrderButton_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (string s in clickOrderList)
{
sb.AppendLine(s);
}
MessageBox.Show(sb.ToString());
}
I'm wondering how to restrict my checkbox from adding to my listbox. At the moment when the user checks the checkbox it will add "Anchovies" to the listbox. What I don't want to happen is when the user deselects the checkbox and re selects it again, "Anchovies" is added to the listbox again (showing two lots of "Anchovies").
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
listBox1.Items.Add("Anchovies");
double total = Convert.ToDouble(textBox2.Text);
total = total + .5;
textBox2.Text = Convert.ToString(total);
}
}
The key is to check if Anchovies already exists on the listBox1 items.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
//If the item is already there, we don't do anything.
if (!listBox1.Items.Contains("Anchovies")) {
listBox1.Items.Add("Anchovies");
double total = Convert.ToDouble(textBox2.Text);
total = total + .5;
textBox2.Text = Convert.ToString(total);
}
}
}
Do it this way
if (checkBox1.Checked)
{
if(!listBox1.Items.Contains("Anchovies"))
listBox1.Items.Add("Anchovies");
double total = Convert.ToDouble(textBox2.Text);
total = total + .5;
textBox2.Text = Convert.ToString(total);
}
To fix this issue, you need to check your list box(for this value, either it is already there or not) before inserting any value in it.
e.g
foreach (var item in listBox1.Items )
{
if(item.ToString() != "Anchovies")
{
listBox1.Items.Add("Anchovies");
}
// other code here.
}
I make a listbox and it works perfectly, I also made a search function, but I want to hide the items in the listbox and show them only when searched through index.
here is my code for adding items
private void Savebtn_Click(object sender, EventArgs e)
{
addTolist(gatherItem());
refreshView();
}
private void addTolist(Person p)
{
Person.listperson.Add(p);
}
private void refreshView()
{
listBox1.Items.Add(getItem());
}
private String getItem()
{
String result = null;
foreach (Person p in Person.listperson)
{
result = p.lastname;
}
return result;
}
and this is my code for search
private void button1_Click(object sender, EventArgs e)
{
int index = listBox1.FindString(textBox6.Text);
if (0 <= index)
{
listBox1.SelectedIndex = index;
}
}
Is there a way for this? thanks :)
There is no easy way to do this with winforms. It a lot easier with WPF. With winforms you will have to remove the items. You could technically use databinding, but its not recommended at all, because listbox is supposed to used directly from your code according the MSDN documentation.
On second thought, you could overdraw the listbox and set the item you want to hide to transparent or something, buts its not easy. You may want to consider storing all your values in an array and then loop through array and only adding the elements you want. Or switch to WPF.
Hope this helps.
You can cover a dummy ListBox on your origin one, and set origin one invisible.
Then you can archive the same effect by writing codes like
class DummyItem {
public string text;
public int index;
public override string ToString() {
return text;
}
}
public void build_dummy() {
listbox_dummy.Items.Clear();
for (int i = 0; i < listbox_origin.Items.Count; i++) {
// replace with your own judgement
if (! should_hide(listbox_origin.Items[i])) {
DummyItem item = new DummyItem();
item.text = listbox_origin.Items[i].ToString();
item.index = i;
listbox_dummy.Items.Add(item);
}
}
}
private void listbox_dummy_SelectedIndexChanged(object sender, EventArgs e) {
var item = (DummyItem) listbox_dummy.SelectedItem;
var index = item.index;
listbox_origin.SelectedIndex = index;
}
The easiest way to do this, is to create a List<string> item that will store removed items (or items that do not match the search-phrase given in textbox1), an int variable that will store how many characters there were the last time the TextChanged event was triggered, and then create a function for your listbox element that activates when the phrase in a textbox is updated:
private void textbox1_TextChanged(object sender, EventArgs e) {}
in this function, there are two things that could happen:
if a character was added to textbox1:
you iterate over the elements in your listbox.
remove the ones that do not contain the phrase in textbox1
if a character was removed from textbox1:
look through the List<string> variable you made to store the values you removed from your listbox
add back each item that fits the text in textbox1 (check for duplicates though)
Here's the code I wrote to use as reference:
private List<string> temporarilyRemovedSongs = new List<string>();
private int previousTextLength = 0;
private void filter_songs_textbox_TextChanged(object sender, EventArgs e)
{
List<string> toRemove = new List<string>();
string text = Tools.Strip(this.filter_songs_textbox.Text.ToLower());
if (text.Length > this.previousTextLength)
{
// a char was added, remove songs that do not start with the search-phrase
foreach (string song in this.songs_list.Items)
{
if (!song.ToLower().Contains(text))
{
this.temporarilyRemovedSongs.Add(song);
toRemove.Add(song);
}
}
foreach (string song in toRemove)
{
this.songs_list.Items.Remove(song);
}
}
else
{
// a char was removed; look through removed songs to add back
foreach (string song in this.temporarilyRemovedSongs)
{
if (song.Contains(text) && !this.songs_list.Items.Contains(song))
this.songs_list.Items.Add(song);
}
}
previousTextLength = text.Length;
}
I am doing a project that uses listbox, I can add items, delete items, update items but I can't search,
this is my code for search
string search = Person.listperson[listBox1.SelectedIndex].lastname;
foreach (String s in search)
{
if (s.Equals(textBox6.Text))
{
//show searched items
MessageBox.Show("Success!");
}
}
can you help me with this?
thanks :)
I have here a code for search,
But it does not apply in the button, how can I apply this on the button?
private void textBox6_TextChanged(object sender, EventArgs e)
{
int index = listBox1.FindString(this.textBox6.Text);
if (0 <= index)
{
listBox1.SelectedIndex = index;
}
}
Try something like this, add a click event to your button and put your code in it. This works for me.
private void button1_Click(object sender, EventArgs e)
{
int index = listBox1.FindString(textBox6.Text);
if (index > -1)
{
listBox1.SelectedIndex = index;
}
}
Not sure what you're trying to do exactly, but here's some samples.
Also, start giving variables useful names. If you come back to this code in a month you'll have no idea what's going on there or what textBox6 is.
To find a string (textBox6) in the entire listperson collection:
var list = Person.listperson.Where(p => p.lastname.Contains(textBox6.Text));
To check if a specific item in listperson has a partial textBox6 value:
var search = Person.listperson[listBox1.SelectedIndex].lastname;
bool success = search.Contains(textBox6.Text);
Or if you'd rather compare the values:
bool success = (search == textBox6.Text);
you can foreach char in a string
string s = "Blippy you";
foreach (char item in s)
{
}
but anywho. try Text.RegularExpressions for string matching.
private void button1_Click(object sender, System.EventArgs e)
{
if (listBox1.FindString("Your String in Textbox 6") != -1)
{
MessageBox.Show("Success!");
}
}