Question

I have a table which populates a dropdownlist called DropDownList_Tracking_Status. The table has 3 columns; ID, TrackingName and Active. When I fill the dropdownlist, I pull every record where Active = "Y".

When I'm reading data into the form, I'm trying to pre-select the appropriate value for DropDownList_Tracking_Status. If the current status is empty (one hasn't been chosen yet), I set it equal to 2. Otherwise, I set it equal to whatever value was previously selected. The problem I have is, if the current Tracking Status is a status that's since been marked as inactive (where Active was set to "N"), it throws an error. Obviously, because it can't pre-select a value that doesn't exist in the dropdownlist.

Any ideas on how to solve this? My current code block looks like this:

if ((DT["TrackingStatus"].ToString() == ""))
{
   DropDownList_Tracking_Status.SelectedValue = "2";
}
else
{
   DropDownList_Tracking_Status.SelectedValue = (DT["TrackingStatus"].ToString());
}

EDIT I'm just going to add that the table that populates the dropdownlist is the one that contains the Active field. The SqlDataReader called DT does not have that field in it. I suppose I could create a query that joins the two and checks the value of Active, but I was hoping there was an easier way. Something that says (in pseudo-code):

If DropDownList_Tracking_Status.SelectedValue = (DT["TrackingStatus"].ToString()); throws you an error, do this instead...
Was it helpful?

Solution

You can place the code in try-catch block as,

try
{
 DropDownList_Tracking_Status.SelectedValue = DT["TrackingStatus"].ToString();
}
catch
{
 DropDownList_Tracking_Status.SelectedValue = "2";
}

It will bind the value if it exists otherwise it will through exception, on which you can asign any default value in catch block.

OTHER TIPS

Is the following possible (possibly preceeded by a check for a null record):

if ((DT["TrackingStatus"].ToString() == ""))
{
   DropDownList_Tracking_Status.SelectedValue = "2"; 
}
else if(DT["Active"] == "N")
{
    DropDownList_Tracking_Status.SelectedValue = "2"; 
}
else
{
   DropDownList_Tracking_Status.SelectedValue = (DT["TrackingStatus"].ToString());
}

UPDATE Adding the Active field to DT seems a good solution OR an alternative would be to see if the dropdown list contains the target value. See the Stack Overflow question here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top