比较DropDownLists

时间:2010-12-08 11:02:43

标签: asp.net-4.0

我有一个包含多个下拉列表的页面,所有页面都填充了相同的值。我想在客户端和服务器端比较它们。

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

2 个答案:

答案 0 :(得分:0)

您需要什么样的比较?如果你没有将它们保存在Session中的List和那个列表中,那么你就永远不能对它们做任何事情,因为你动态添加它们。添加您创建它们的下拉列表(当Page.IsPostBack == false时,这应该是我)并将该列表保留在会话中。在回发上,从列表中加载下拉列表。您可以使用您保留的列表进行比较。

答案 1 :(得分: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;
    }