如果重复选择,则下拉列表选定索引设置为 0
本文关键字:索引 设置 下拉列表 选择 如果 | 更新日期: 2023-09-27 18:36:35
我有一个 linq 查询,它检查所有 6 个下拉列表是否有任何重复。
为此,目前我为所有下拉列表设置 SelectedIndex 为 0。取而代之的是,我想要这两个下拉菜单。SelectedIndex=0 具有相同的 SelectedValue。
var allIndexes = new List<int>
{
drpdwnlst_Seq1.SelectedIndex,
drpdwnlst_Seq2.SelectedIndex,
drpdwnlst_Seq3.SelectedIndex,
drpdwnlst_Seq4.SelectedIndex,
drpdwnlst_Seq5.SelectedIndex,
drpdwnlst_Seq6.SelectedIndex
};
var noSelectedIndexIsTheSame = allIndexes.Where(x => x != 0)
.GroupBy(x => x)
.All(x => x.Count() == 1);
if (!noSelectedIndexIsTheSame)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AdminUserError", "alert('Selection Rrepeated.'); ", true);
drpdwnlst_Seq1.SelectedIndex = 0;
drpdwnlst_Seq2.SelectedIndex = 0;
drpdwnlst_Seq3.SelectedIndex = 0;
drpdwnlst_Seq4.SelectedIndex = 0;
drpdwnlst_Seq5.SelectedIndex = 0;
drpdwnlst_Seq6.SelectedIndex = 0;
}
您可以将列表更改为以下定义,(以便您可以保留大部分逻辑)
List<KeyValuePair<DropDownList, int>> allIndexes = new List<KeyValuePair<DropDownList, int>>
{
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq1, drpdwnlst_Seq1.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq2, drpdwnlst_Seq2.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq3, drpdwnlst_Seq3.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq4, drpdwnlst_Seq4.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq5, drpdwnlst_Seq5.SelectedIndex),
new KeyValuePair<DropDownList, int>(drpdwnlst_Seq6, drpdwnlst_Seq6.SelectedIndex)
};
var groups = allIndexes.Where(x => x.Value != 0).GroupBy(x => x.Value);
boolean noSelectedIndexIsTheSame = groups.All(g => g.Count() == 1);
if (!noSelectedIndexIsTheSame)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AdminUserError", "alert('Selection Rrepeated.'); ", true);
foreach (var g in groups)
{
if (g.Count() == 1)
{
continue;
}
foreach (var kvp in g)
{
kvp.Key.SelectedIndex = 0;
}
}
}
这样,您就有了组合框的引用 + 当前选定的索引,按 KeyValuePair.Value 分组,并且您有一个单独的布尔值检查是否没有相同的索引。如果是,它将循环组,如果每个组找到超过 1 个,请重置这些组