c# gridview multiple filter - c#

Can I make multiple filter in gridview? So far I have three separate methods for each kind of filtering. I want to be able to do something like this. First choose from combobox value which will be shown and then from this filtered list, I would like to be able to search by using textbox for something else.
private void button9_Click(object sender, EventArgs e)
{
var result = list3.Where(Srodek => Srodek.Srodek.ID.Device == textBox2.Text).ToList();
dataGridView4.DataSource = result;
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
var result = list3.Where(Srodek => Srodek.Srodek.category1 == comboBox1.SelectedItem.ToString()).ToList();
dataGridView4.DataSource = result;
}
Now when I choose some value from combobox it show what I want in gridview, but later when I insert something in textbox and click the button, it is filtering the whole list not this one already filtered by combobox. How can I achieve it?

Try FilterDataGrid() calling on both events:
private void button9_Click(object sender, EventArgs e)
{
FilterDataGrid();
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
FilterDataGrid();
}
private void FilterDataGrid()
{
var _text = Convert.ToString(textBox2.Text);
var _comboText = ! string.IsNullOrEmpty(comboBox1.Text) ? Convert.ToString(comboBox1.SelectedItem) : string.Empty;
var result = list3.Where(Srodek => Srodek.Srodek.category1 == _comboText || Srodek.Srodek.ID.Device == _text).ToList();
//
dataGridView4.DataSource = result;
}
Hopes this helps u.

I suppose the type of element in list3 is T:
private void button9_Click(object sender, EventArgs e)
{
if(dataGridView4.DataSource is IEnumerable<T>){
var result = ((IEnumerable<T>)dataGridView4.DataSource).Where(Srodek => Srodek.Srodek.ID.Device == textBox2.Text).ToList();
dataGridView4.DataSource = result;
}
}

Make a global property that will host your list so that everytime you perform a query on the list you perform a query on your up to date list that has already been filtered.

You aren't changing the source of you filter, so you are filtering on the same set each time. One option would be to have the original dataset and a filtered dataset, then when you filter the original save the results in the filtered set.

Related

How to filter a specific record from BindingList c#

I have a bindinglist and after populating it, the list will be bind to a listbox.
private BindingList<VersionControlLabel> allTfsLabelList = new BindingList<VersionControlLabel>();
Versioncontrollabel class contains Name,version no, modified date etc..
Current implementation is when loading the form all the versions are load into the listbox then we have go through every item to find the specific one. Instead I want to add a textbox and when I type I want to show the record which has a exesiting word in textbox.
if user type the version number continuously the listbox should show the matching record
As enumrator properties are not available when I use the linq. How to do this?
I implemented something like this. But its not working. its not linq
private void txtSearchLabel_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(txtSearchLabel.Text))
{
string text = txtSearchLabel.Text;
foreach (VersionControlLabel part in allTfsLabelList)
{
if(part.LabelId.ToString().Contains(text))
{
lstLabels.DataSource = part;
}
else
{
lstLabels.DataSource = allTfsLabelList;
}
}
}
}
If you want to just do ad hoc filtering then you can do something like this:
private List<string> allItems = new List<string>();
private void DisplayFilteredList()
{
var searchText = textBox1.Text.Trim();
listBox1.DataSource = searchText.Length == 0
? allItems
: allItems.Where(s => s.Contains(searchText)).ToList();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DisplayFilteredList();
}

Add and delete text to/from ListBox hosted in WinForm using C#

I am working on a simple application that to add/delete string/s into an array and show that in ListBox.
My code shows only the latest value that was typed into the textBox and
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
List<string> ls = new List<string>();
ls.Add(add);
String[] terms = ls.ToArray();
List.Items.Clear();
foreach (var item in terms)
{
List.Items.Add(item);
}
}
private void Delete_Click(object sender, EventArgs e)
{
}
This code makes no sense. You are adding one single item to a list, then convert it to an array (still containg one item) and finally loop through this array, which of course adds one item to the previously cleared listbox. Therefore your listbox will always contain one single item. Why not simply add the item directly?
private void Add_Click(object sender, EventArgs e)
{
List.Items.Add(textBox1.Text);
}
private void Delete_Click(object sender, EventArgs e)
{
List.Items.Clear();
}
Also clear the listbox in Delete_Click instead of Add_Click.
If you prefer to keep the items in a separate collection, use a List<string>, and assign it to the DataSource property of the listbox.
Whenever you want the listbox to be updated, assign it null, then re-assign the list.
private List<string> ls = new List<string>();
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
// Avoid adding same item twice
if (!ls.Contains(add)) {
ls.Add(add);
RefreshListBox();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Delete the selected items.
// Delete in reverse order, otherwise the indices of not yet deleted items will change
// and not reflect the indices returned by SelectedIndices collection anymore.
for (int i = List.SelectedIndices.Count - 1; i >= 0; i--) {
ls.RemoveAt(List.SelectedIndices[i]);
}
RefreshListBox();
}
private void RefreshListBox()
{
List.DataSource = null;
List.DataSource = ls;
}
The problem with code is quite simple. Instead of adding new item to list your code creates new list with one added item only. I am trying to interpret functions of program and they seem to be:
Enter new text into top level text box.
If Add button is clicked your item goes on top of the list (if it's bottom see end of my answer).
If item(s) is selected in list and Delete is clicked selected item(s) is/are deleted.
To achieve this you should first insert text on top of the list by using Add_Click code, than delete selected items using Delete_Click code. There is additional code to guard against inserting empty or white space only strings plus trimming of leading and trailing white space.
private void Add_Click(object sender, EventArgs e)
{
// Since you do not want to add empty or null
// strings check for it and skip adding if check fails
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text)
{
// Good habit is to remove trailing and leading
// white space what Trim() method does
List.Items.Insert(0, textBox1.Text.Trim());
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Get all selected items indices first
var selectedIndices = List.SelectedIndices;
// Remove every selected item using it's index
foreach(int i in selectedIndices)
List.Items.RemoveAt(i);
}
To complete adding and deleting logic I would add Delete All button which would just call List.Items.Clear(). If you prefer to add text at the end just use Add method form #Olivier Jacot-Descombes answer.
You can use in C#:
private void Delete_Click(object sender, EventArgs e)
{
if(myList.Contains(textbox1.value))//if your list containt the delete value
{
myList.Remove(textbox1.value); //delete this value
}
else
{
//the list not containt this value
}
}
and you can use the same method for validate if a value exist when try to add
private void AddItem()
{
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text))
{
var newItem = textBox1.Text.Trim();
if (!List.Items.Contains(newItem))
{
List.Items.Add(newItem);
// Alternative if you want the item at the top of the list instead of the bottom
//List.Items.Insert(0, newItem);
//Prepare to enter another item
textBox1.Text = String.Empty;
textBox1.Focus();
}
}
}
private void Add_Click(object sender, EventArgs e)
{
AddItem();
}
Private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
AddItem();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Remove every selected item using it's index
foreach(var item in List.SelectedItems)
{
List.Items.Remove(item);
}
}

Edit Items in a ListBox

I am creating a program using WinForms so users can input info into textboxes on one form which then are saved into a Listbox on another form. I would like to be able to edit the items saved in the listbox by opening the original form on a button click. Really struggling with it as I can't think of the code and I can't seem to find a solution.
My Code:
private void btnAdd_Click(object sender, EventArgs e)
{
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.ShowDialog();
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
listBoxRooms.Items.Add(newRoomDisplayForm.value);
}
newRoomDisplayForm.Close();
}
private void btnRemove_Click(object sender, EventArgs e)
{
this.listBoxRooms.Items.RemoveAt(this.listBoxRooms.SelectedIndex);
}
private void btnEdit_Click(object sender, EventArgs e)
{
}
So i've got a Add and Remove button which work perfectly just need a solution to the edit button.
Thanks in advance
I'm guessing newRoomDisplayForm.value is a property or a public member inside the form. You just need to do something like this:
private void btnEdit_Click(object sender, EventArgs e)
{
if(listBoxRooms.SelectedIndex < 0) return;
var tmpValue = listBoxRooms.Items[listBoxRooms.SelectedIndex].ToString();
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.value = tmpValue;
newRoomDisplayForm.ShowDialog();
//TODO: inside "newRoomDisplayForm" set the value to the textbox
// ie.: myValueTextBox.Text = this.value;
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
// replace the selected item with the new value
listBoxRooms.Items[listBoxRooms.SelectedIndex] = newRoomDisplayForm.value;
}
}
Hope it helps!
You can simply remove the listitem in that specific position, create a new item and add it again. it's kind of replacement.

Winforms - Stop Dropdown of Combobox during DropDown event

I need to implement a ComboBox, which acts as follows:
When Click on the ComboBox, the client calling API method and updates the combobox items with the response.
My problem is, when I have 0 results - I want the ComboBox not to open (It has 0 items).
Is there a way to do that?
This is my current code:L
private void Combo_DropDown(object sender, EventArgs e)
{
// Private method which addes items to the combo, and returns false if no itmes were added
if (!AddItemsToComboBox())
{
// This is not working
Combo.DroppedDown = false;
}
}
You can make the DropDownHeight as small as possible (1). For example:
int iniHeight;
private void Form1_Load(object sender, EventArgs e)
{
iniHeight = Combo.DropDownHeight;
}
private void Combo_DropDown(object sender, EventArgs e)
{
Combo.DropDownHeight = (AddItemsToComboBox() ? iniHeight : 1);
}

how to compare selectedIndex to a string in listBox

I want to create a if statement that recognizes which string has been removed from a specific list box. I thought i could do an if statement similar to the one below and get it to work but it tells me it has invalid arguements - if anyone can guide me it would appreciated
private void button2_Click(object sender, EventArgs e)
{
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
if(listBox2.Items.RemoveAt(listBox2.SelectedItems.ToString().Equals("Test")))
{
picturebox.Image = null;
}
}
You need to check the SelectedItem before removing it:
private void button2_Click(object sender, EventArgs e)
{
if (listBox2.SelectedIndex != -1)
{
if (listBox2.SelectedItem.ToString().Equals("Test")))
picturebox.Image = null;
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
}
}
I’ve also added a check to ensure that an item is actually selected (since you would get errors otherwise).
Your issue is that you are calling ListBox.Items.RemoveAt(int index) and passing in a boolean value: listBox2.SelectedItems.ToString().Equals("Test")).
In addition, you're removing the item first, and then calling RemoveAt again, which will actually remove a different item (whatever is now at that index), or throw an exception if you've gone outside of the bounds of your ListBox collection.
You should first check if your selected item equals "Test", and then remove the item from your ListBox, like so:
private void button2_Click(object sender, EventArgs e)
{
// SelectedIndex returns -1 if nothing is selected
if(listBox2.SelectedIndex != -1)
{
if( listBox2.SelectedItem.ToString().Equals("Test") )
{
picturebox.Image = null;
}
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
}
}
You should do something like :
String deletedString = listBox2.Items.ElementAt(listBox2.SelectedIndex).ToString();
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
if(listBox2.Items.RemoveAt(deletedString == "Test"))
{
picturebox.Image = null;
}
It might not compile (Check if Items has SelectedItem property).

Categories

Resources