2010-12-08 29 views
0

我有一个页面,其中包含几个下拉列表,所有填充相同的值。我想在客户端以及服务器端进行比较。比较DropDownLists

问题是,下拉列表是动态生成的,因为它们的数量可能会有所不同。

回答

0

客户端比较:

<script type="text/javascript"> 
     function CompareSelectedValues(dropDown1ID, dropDown2ID) { 
      var DropDownList1 = document.getElementById(dropDown1ID); 
      var DropDownList2 = document.getElementById(dropDown2ID); 
      if (DropDownList1.selectedIndex != -1 && DropDownList2.selectedIndex != -1) { 
       if (DropDownList1.options[DropDownList1.selectedIndex].value != DropDownList2.options[DropDownList2.selectedIndex].value) 
        alert('not same'); 
      } 
     } 
    </script> 




经典服务器端与C#比较:

private bool AreDropDownListValuesEqual(DropDownList ddlist1, DropDownList ddlist2) 
    { 
     // Check for invalid input or different number of items for early return 
     if (ddlist1 == null || ddlist2 == null || ddlist1.Items.Count != ddlist2.Items.Count) 
     { 
      return false; 
     } 

     // Check items one by one. We need a nested loop because the list could be sorted differently while having the same values! 
     foreach (ListItem outerItem in ddlist1.Items) 
     { 
      bool hasMatch = false; 
      foreach (ListItem innerItem in ddlist2.Items) 
      { 
       if (innerItem.Value == outerItem.Value && innerItem.Text == outerItem.Text) 
       { 
        hasMatch = true; 
        break; 
       } 
      } 

      if (!hasMatch) 
      { 
       return false; 
      } 
     } 

     // All items from ddlist1 had a match in ddlist2 and we know that the number of items is equal, so the 2 dropdownlist are matching! 
     return true; 
    } 
0

你需要什么样的比较?如果您没有将它们保留在会话中的列表和列表中,那么您将无法对它们进行任何操作,因为它们是动态添加的。添加你创建它们的下拉列表(这应该是我在Page.IsPostBack == false时)并在会话中保留该列表。在回传时,从列表中加载您的下拉列表。您可以使用您保留的列表进行比较。