2

I have a dropdown list as below:

DropDownList1.DataSource = Students.GetStudents();
DropDownList1.DataBind();
-----------

I have a DataAccess Class as below:

public IEnumerable<StudentEntity> GetStudents()
{
List<StudentsEntity> studentsList = new List<StudentsEntity>();
studentsList = Service.GetList()  // some service getting a list of sutdents

return new BindingList<StudentEntity>(studentsList);
}

I have a DataObject Class as below:

public class StudentEntity : IComparable
{
  public string fullname { get {return firstName +", "+ lastName;}
  public string ID {get; set;}
  public string Height {get; set;}
  public string Firstname {get; set;}
  public string Lastname {get; set;}
  public int CompareTo(object obj)
  {
     StudentEntity entity = (StudentEntity) obj;
     return Lastname.CompareTo(entity.Lastname);
  }
}

At the UI level - the 'Students Fullname' is displayed in the dropdown list, so how can I get the 'ID' of the Selected Student from the DropDown List?

Cœur
  • 37,241
  • 25
  • 195
  • 267
saklo
  • 111
  • 1
  • 11

2 Answers2

1

Get the selected item from the DropDownList and cast it to an object of the type StudentEntity. Afterwards you can get the ID of that object. Pseudo code:

var selectedItem = myDropDown.SelectedItem as StudentEntity;
var ID = selectedItem.ID;

Edit:

'hvd' commented me correctly. Since this is in a webcontext, you'll have to achieve this a bit different. You can set the DataTextField and the DataValueField of the DropDownList. Bind the ID to the DataValueField and when you get the SelectedItem, get the Value-property and you have the ID.

var selectedItem = myDropDown.SelectedItem;
var ID = selectedItem.Value;
Abbas
  • 14,186
  • 6
  • 41
  • 72
  • 1
    Perhaps I'm misreading the documentation, and I can't check right now, but what I see is that [`SelectedItem`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selecteditem.aspx) isn't the data item, it's a `ListItem` object, which will not contain any `StudentEntity` properties. –  Oct 17 '12 at 14:31
  • You're right, didn't realise it was about web controls... Check edited answer :) – Abbas Oct 17 '12 at 14:36
0

In the event handler:

var id = ((StudentEntity)sender).Id;
DaveDev
  • 41,155
  • 72
  • 223
  • 385
  • 2
    What event handler? If it's an event of the dropdown list, the sender will be the dropdown list, not the `StudentEntity`. –  Oct 17 '12 at 14:27
  • Then it should be: var id = ((StudentEntity)((DropDownList)sender).SelectedItem).ID; – Abbas Oct 17 '12 at 14:28