سؤال

In my c# windows forms application,I have a list of Students (Student). ArrayList students = new ArrayList(); There is a textbox and listbox.

Student has propery called studentId. So when I enter a number in textbox, application should filter out the array list (auto complete) and shown the suggestions in the listbox.

private void textBoxNameForID_TextChanged(object sender, EventArgs e)
{
      // MessageBox.Show("Changed: " + " Text is: " + textBoxNameForID.Text);
      if (studentsSortedList != null) 
      {     
            foreach (Student stu in students)
            {       
                 bool contains = stu.ID.ToString().Contains(textBoxNameForID.Text);
                 if (contains) 
                 {
                      MessageBox.Show("Changed: " + " Text is: " + textBoxNameForID.Text);
                 }
            }
       }
 }

I have tried it and no results found for my expectations.Please help me out with this

هل كانت مفيدة؟

المحلول

This is StartsWith for ID
Use a HasSet. List, or Array for studentHS
Even if ID is an Integer you will need to use string

public IEnumerable<string> Students 
{
    get
    {
        return studentsSS
               .Where(x => x.StartsWith(studentID));
    }
}

نصائح أخرى

Change the ArrayList to List<Student>, then just set the data source of your listbox with the filtered list:

private void textBoxNameForID_TextChanged(object sender, EventArgs e)
{
   listBox1.DataSource = students.Where(s => s.Id.StartsWith(textBoxNameForID.Text)).ToList();
}

Set the listBox DisplayMember as well with the name of a property from the Student class. As an example:

listBox1.DisplayMember = "Display";

where Display can be : public string Display { get { return Id + ":" + Name; } }

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top