I am trying to populate a ddl (which works) and when I select the ‘FirstName’ the textboxes are populated for editing.
When i step through the program the (drp_Customer.SelectedItem.Value) is always ’23’ which is the last ‘Id’ in my DB.
The fileds get populated but with 23’s details..
I am thinking I need to make sure the ddl’s details match up.
Here is my code.
It is only rough as i am trying to show somebody how it might work.
using (CustomerDataContext obj = new CustomerDataContext())
{
// Get fields for drp_Customer
// ===========================
var allCustomers = from c in obj.Customers
orderby c.FirstName
select new
{
c.FirstName,
c.CustomerId
};
foreach (var item in allCustomers)
{
drp_Customer.Items.Add(item.FirstName);
drp_Customer.SelectedItem.Value = item.CustomerId.ToString();
}
drp_Customer.DataBind();
if (drp_Customer.SelectedItem.Text == " -- Select Customer -- ")
{
lbl_message.Text = "Please select a customer to update";
}
else if (drp_Customer.SelectedItem.Text != " -- Select Customer -- ")
{
Customer myCust = obj.Customers.SingleOrDefault(c => c.CustomerId == Convert.ToInt32
(drp_Customer.SelectedItem.Value));
if (myCust != null)
{
txt_FirstName.Text = myCust.FirstName;
txt_Surname.Text = myCust.Surname;
txt_HouseNumber.Text = myCust.HouseNumberName;
txt_Address.Text = myCust.Address;
txt_Town.Text = myCust.Town;
txt_Telephone.Text = myCust.Telephone;
txt_Postcode.Text = myCust.Postcode;
}
}
The reason why always the last item is selected is this loop:
The last item will be the selected item since you’re always changing it. You need to assign it outside of the loop. But you haven’t shown which customer is the correct selected customer currently.
Note that you also can use
DataSource+DataBind: