Question

I have a Listbox called TeachersList I populate it with string values from a database. Now I want to remove any thing that was imported as empty. When the list loads it gives blank items and I don't want this. I tried using a for loop but it doesn't work. this what I used

int CountEmptyValues = TeachersList.Items.Count;
for (int i = CountEmptyValues - 1; i >= 0; i--)        
    if (TeachersList.Items[i].ToString() == " ")
    {
        TeachersList.Items.RemoveAt(i);
    }

Any kind of help would be highly appreciated.

And here is how I added items from the database into the listbox

                MySqlConnection TeachersDB = new MySqlConnection();
                string SchoolsDbString = TeachersDB.ConnectionString = @"server=localhost;Port=3306; user id=root; password=test; database=" + Globals.DBChosen;
                MySqlDataAdapter SubjectsAdapter = new MySqlDataAdapter("Select " + SearchByField.Text + " From users", TeachersDB);
                DataSet Dataset = new DataSet();
                TeachersDB.Open(); 

                SubjectsAdapter.Fill(Dataset); 
                TeachersList.DataSource = Dataset.Tables[0];
                TeachersList.DisplayMember = SearchByField.Text; 
Was it helpful?

Solution

You can filter the table using Linq easily, we create a DataView out of it and set the DataView as DataSource. You're done.

string searchBy = SearchByField.Text;
TeachersList.DataSource = Dataset.Tables[0].AsEnumerable().Where(x => !string.IsNullOrWhiteSpace(x.Field<string>(searchBy))).AsDataView();
TeachersList.ValueMember = searchBy;

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top