How to set the stored value to a dropdown list when the dropdown has a databinding happening during page load?

Issue

WorkflowGen assigns values to your form fields before the Page_Load event occurs, so any databinding of a drop-down list (e.g. read values from database) that happens in your Page_load section will reset the selected value.

Solution

After you have re-bound your combo box (i.e., your combo box has been re-populated with the options you retrieved from an external source), you must set the originally selected value manually.

After your DropDownList databinding method is called, run the below method by passing the target DropDownList as a parameter.

Add this method in your code:

C#

private void SetDropDownListSelectedValue(DropDownList TargetDDL)
{ 
   if (TargetDDL != null) { 
      string WFGFieldName = TargetDDL.ID; 
      string SelectedValue = FormData.Tables[Table1].Rows[0][WFGFieldName].ToString(); 
      ListItem li = null; 
      li = TargetDDL.Items.FindByValue(SelectedValue); 
      if (li != null) { 
        int index = TargetDDL.Items.IndexOf(li); TargetDDL.SelectedIndex = index; 
      }
 }
}

VB

Private Sub SetDropDownListSelectedValue(ByVal TargetDDL As DropDownList) 
 If ((Not (TargetDDL) Is Nothing)) Then
  Dim WFGFieldName As String = TargetDDL.ID 
  Dim SelectedValue As String = FormData.Tables(Table1).Rows(0)(WFGFieldName).ToString 
  Dim li As ListItem = Nothing 
  li = TargetDDL.Items.FindByValue(SelectedValue) 
  If (Not (li) Is Nothing) Then
   Dim index As Integer = TargetDDL.Items.IndexOf(li) 
   TargetDDL.SelectedIndex = index 
  End If
 End If
End Sub

Hello,

It works when you add quotes to Table1

string SelectedValue = FormData.Tables[“Table1”].Rows[0][WFGFieldName].ToString();