2

I have a c# winform with textboxes, connected via Entity Framework to a table, called Candidates (it has 700 records). I'm using a BindingSource named candidatesBindingSource. Everything works as I want.

There is just one thing. I'm trying to implement searching candidates with surnames. So i have a Textbox, called textSurname and a Button with this code for searching through my records:

var searchResults = (from a in _context.Candidates where (a.Surname.Contains(textSurname.Text)) select a.Id).ToList();
if (searchResults.Count > 0)
{
    // Id of a record in searchResults is correct
    var position = searchResults[0];
    // This line moves focus to a wrong record
    candidatesBindingSource.Position = position; // 
}

If a record is found, I can get its Id. And here I have a problem. How can I reposition my candidatesBindingSource to the record with the Id from my searchResults? For example, if I have an Id = 2638, the code above repositions my candidatesBindingSource to the last record. I'm suspecting that this part candidatesBindingSource.Position actualy works as recordcount (700 in my table) and is unable to go to the record nr. 2638 (not to the record with this Id). Am I right? So how can I implement a GOTO record with my found Id? Do I really have to use a For loop with MoveNext command to compare my searched Id with all Id's?

Any hint would be very appreciated.

demonplus
  • 5,613
  • 12
  • 49
  • 68
Vladimir
  • 75
  • 8

3 Answers3

3

Ok, so this is how you initialize you binding source

candidatesBindingSource.DataSource = _context.Candidates.ToList();

Then you don't need to search the database, you can search the data source list using the List.FindIndex method like this:

var candidateList = (List<Candidate>)candidatesBindingSource.DataSource;
var searchText = textSurname.Text;
var firstMatchIndex = candidateList.FindIndex(c => c.Surname.Contains(searchText));
if (firstMatchIndex >= 0)
     candidatesBindingSource.Position = firstMatchIndex;
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
1

I think you should set to candidatesBindingSource.Position index of item and not id. That post will help you to get index of item correctly, witout read whole data again. Get Row Index in a list by using entity framework

Also you can try get index from your binding source.

Community
  • 1
  • 1
Mitklantekutli
  • 410
  • 1
  • 3
  • 16
0

If you create a list out of your context it will have the same indexing as the databinding you set on your form. To set your form to look at the result of your search you can use the a match from the FindIndex() method of the list, and then set your .Position to that index.

using (Candidates _context = new Candidates())
{    
    var candidateList = _context.Candidate.ToList();
    var firstCandidateMatchIndex = candidateList.FindIndex(c => 
        c.Surname.Contains(textSurname.Text));
    if (firstCandidateMatchIndex >= 0)
        candidateBindingSource.Position = firstCandidateMatchIndex;
}