Sunday, April 3, 2011

SelectedIndex = -1 with data bound Combo

Is there any equivalent to this when a combo is data bound? I've been through this hundreds of times before, but I'm having a brain freeze moment.

From stackoverflow
  • In asp.net the closest you could get is to add in a false item such as "---Select Something---" and have it as index 0, then you would set and perform checks on index 0 instead of -1.

    Example:

    dropdownlist1.datasource = DT
    dropdownlist1.datatextfield = "EmployeeName"
    dropdownlist1.datavaluefield = "EmployeeID"
    dropdownlist1.databind
    
    dropdownlist1.items.insert(0, "---"Select An Employee---")
    
    dropdownlist1.selectedindex = 0
    

    Then during your validation you could make sure to check to make sure selectedindex <> 0

  • A trick I've done in the past, is that if your DataValue field is going to be a numeric field (such as an Id), you can assign a range validator object to it and check that the value itself is greater than 0. I then create my "select" item to have a value of -99 and I can then perform validation on the client side.

0 comments:

Post a Comment