How to cycle through entries in Linq to SQL from query?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fuzz13
    New Member
    • Jun 2010
    • 110

    How to cycle through entries in Linq to SQL from query?

    I have a small application using linq to sql to save entries into a database for name, email, phone, and birthday. I am able to save an entry and then call the first one back but if I have multiple entries with the same name for example, I don't know how to return one, prompt the user if its the one they want, and if not return the next one. My code for calling the first one looks like this:
    Code:
     do
                    {
                        var contact = (from c in db.tblContacts
                                       where c.Name == txtbxSearch.Text
                                       //where c.Birthday == Convert.ToDateTime(txtbxSearch.Text)
                                       //where c.Email == txtbxSearch.Text
                                       //where c.Phone == int.Parse(txtbxSearch.Text)
                                       select c).FirstOrDefault();
                        
                        txtbxName.Text = contact.Name;
                        txtbxEmail.Text = contact.Email;
                        txtbxBirthday.Text = contact.Birthday.ToString();
                        txtbxPhone.Text = contact.Phone.ToString();
                        
                        result = MessageBox.Show("Is this the entry you wanted?", "Entry Found", MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question);
                    }
                    while (result == DialogResult.No);
    Ideally I would like that when the user clicks "no" it goes to the next entry matching the search criteria. Can anyone shed some light on this? Thanks.
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    Don't use FirstOrDefault, do it like that
    Code:
    var contacts = from ...
                   select ...;
    
    
    foreach(var contact in contacts) {
       contact.Name ...
       contact.Email ...
    
      //Here you could ask the user
      if(User clicks yes) {
        //do something
        break; //exit the foreach
      }
    }

    Comment

    Working...