question

fahimeabouhamze-7844 avatar image
0 Votes"
fahimeabouhamze-7844 asked fahimeabouhamze-7844 answered

Bind value to combobox in Edit mode in windows form app C#

I have a list in which I put add and edit button. both of two button use the same form. I use comboBox to add or edit person's role .This list is about the different role that a person can have so I need person's Id from table persons. In this case I add a combobox for user to lookup in person's table. "add" button work successfully but I do not know how to fetch person's name into combobox in edit mode. my code is like bellow :

in action of form load:

      var person = (from b in db.PersonRepository.GetAll()
                   select new { b.Id , Fullname = b.LName + " " + b.Name + "-" + 
          b.Id.ToString()  } ).ToList();
      person.Insert(0, new 
       {
          Id = 0,
            Fullname = "Please select one"
     });
     cmbSelectName.DisplayMember = "Fullname";
     cmbSelectName.ValueMember = "Id";
     cmbSelectName.DataSource = person;

and also I put code for edit record bellow above code :

             if (PersonRoleId != 0)
     {
         this.Text = "edit";
         btnAddOrEditPersonRole.Text = "edit";
         var personRole = db.PersonRoleRepository.GetById(PersonRoleId);
         var person1 = (from b in db.PersonRepository.GetAll()
                        where b.Id == personRole.PId
                        select new { b.Id, Fullname = b.LName + " " + b.Name + "-" + 
       b.Id.ToString() }).ToList().FirstOrDefault();

            
         cmbSelectName.SelectedValue = person1.FullName;
     
         txtRolePost.Text = personRole.PersonPost;
         chbRolePersonStatus.Checked =(bool) personRole.Status;
     }
 }
windows-forms
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

In regards to edit mode, what event is your code working in? perhaps TextChanged

Also, you don't need .ToList
b.Id.ToString() }).FirstOrDefault();

1 Vote 1 ·

Hi Karen
form load
cmbSelectName.SelectedValue = person1.FullName;
I want when I am on a current row and click on edit button The combobox will fill with the data
no not in textChanged.
I Remove .ToList()

0 Votes 0 ·

1 Answer

fahimeabouhamze-7844 avatar image
0 Votes"
fahimeabouhamze-7844 answered

hi Karen

I finally solve it.
I use
cmbSelectName.Text = person1.FullName;
instead of
cmbSelectName.SelectedValue = person1.FullName;

thank you very much giving me some note

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.