简体   繁体   English

添加带有SelectedValue的动态RadioButtonList

[英]Adding Dynamic RadioButtonList with SelectedValue

Please bear with me if I am not able to properly phrase the question. 如果我无法正确表达问题,请忍受。

This is code which dynamically adds a ListControl (RadioButtonList) to a form: 这是将代码动态添加到表格的ListControl(RadioButtonList)的代码:

protected void Page_Load(object sender, EventArgs e)
{
    RadioButtonList r = GetRadioButtonList("Status", "Yes, No", "Yes, No", "No, Yes");
    form1.Controls.Add(r);
}

private RadioButtonList GetRadioButtonList(string id, string keys, string values, string selectedValues)
{
    RadioButtonList list = new RadioButtonList();
    list.ID = id;
    AddListItems(list, keys, values, selectedValues);
    return list;
}

private void AddListItems(ListControl control, string keys, string values, string selectedValues)
{
    string[] key = keys.Split(',');
    string[] value = values.Split(',');

    if (key.Count() == value.Count())
    {
        for (int i = 0; i < key.Length; i++)
        {
            ListItem item = new ListItem(key[i].Trim(), value[i].Trim());
            control.Items.Add(item);
        }
    }

    foreach (string selectedValue in selectedValues.Split(','))
    {
        foreach (ListItem item in control.Items)
        {
            if (item.Value.Trim().Equals(selectedValue.Trim()))
            {
                item.Selected = true;
            }
        }
    }
}

I have pasted only required, minimum, and reproducible code here. 我在这里仅粘贴了必需的,最少的和可复制的代码。

Since the function AddListItems accepts ListControl and CheckBoxList(ListControl) can have more than one selection, I first accidentally happened to pass two selected values to the RadioButtonList, when replacing the CheckBoxList with the RadioButtonList. 由于函数AddListItems接受ListControl,并且CheckBoxList(ListControl)可以有多个选择,因此当我用RadioButtonList替换CheckBoxList时,我首先偶然碰巧将两个选定的值传递给RadioButtonList。 It produced unexpected results. 它产生了意外的结果。

Out of curiosity, I intentionally passed two values as selected items to see what happens. 出于好奇,我特意传递了两个值作为选定项,以查看会发生什么。

RadioButtonList r = GetRadioButtonList("Status", "Yes, No", "Yes, No", "No, Yes" ); RadioButtonList r = GetRadioButtonList(“ Status”,“ Yes,No”,“ Yes,No”, “ No,Yes” );

In this case, the item.selected would be called twice. 在这种情况下,item.selected将被调用两次。 I believe the selected item should be the item which was selected last, which is "Yes". 我认为所选项目应该是最后选择的项目,即“是”。

On debugging, the selected item is "Yes", which is the last one. 在调试时,所选项目为“是”,这是最后一项。 Fair enough! 很公平!

Now, when the page is displayed in the browser, "No" is displayed. 现在,当页面显示在浏览器中时,将显示“否”。

What is causing the difference in debugging and actual output? 是什么引起调试和实际输出的差异?

Edit 编辑

Investigating further, I passed three values to check what would happen ... 进一步调查,我传递了三个值来检查会发生什么...

RadioButtonList r = GetRadioButtonList("Status", "Yes, No, Maybe", "Yes, No, Maybe", "Yes, No, Maybe");
RadioButtonList r = GetRadioButtonList("Status", "Yes, No, Maybe", "Yes, No, Maybe", "Maybe, No, Yes");
RadioButtonList r = GetRadioButtonList("Status", "Yes, No, Maybe", "Yes, No, Maybe", "No, Yes, Maybe");
RadioButtonList r = GetRadioButtonList("Status", "Yes, No, Maybe", "Yes, No, Maybe", "No, Yes");

It did not matter which item was selected last or in whatever order, the last item of the selected items of the RadioButtonList will be displayed as selected. 最后选择哪个项目或以什么顺序无关紧要,RadioButtonList中所选项目的最后一个项目将显示为选中状态。

Edit 2 编辑2

Thanks to Tim's answer, I ended up with this function. 多亏了Tim的回答,我终于有了这个功能。

private void AddListItems(ListControl control, string keys, string values, string selectedValues)
{
    string[] key = keys.Split(',');
    string[] value = values.Split(',');

    if (key.Count() == value.Count())
    {
        for (int i = 0; i < key.Length; i++)
        {
            ListItem item = new ListItem(key[i].Trim(), value[i].Trim());
            control.Items.Add(item);
        }
    }

    foreach (ListItem item in control.Items)
    {
        if (control is CheckBoxList)
        {
            foreach (string selectedValue in selectedValues.Split(','))
            {
                if (item.Value.Trim().Equals(selectedValue.Trim()))
                {
                    item.Selected = true;
                }
            }
        }
        else
        {                
            if (item.Value.Trim().Equals(selectedValues.Split(',').Last().Trim()))
            {
                item.Selected = true;
                break;
            }
        }
    }
}

The RadioButtonList does not support multi-selection but you provide "No, Yes" as the selected items. RadioButtonList不支持多选,但您提供“否,是”作为所选项目。 If you want to select the last item ("Yes") only: 如果只想选择最后一项(“是”):

RadioButtonList r = GetRadioButtonList("Status", "Yes, No", "Yes, No", "Yes");

You are using your function to return a RadioButtonList which supports single-selection only. 您正在使用函数返回仅支持RadioButtonList But you are assigning two selected values. 但是您要分配两个选定的值。 Now are you wondering why the "wrong" item is selected. 现在,您想知道为什么选择了“错误”项目。 Why? 为什么?

Item.selected is called twice, which does not mean two values are assigned. Item.selected被调用两次,这并不意味着分配了两个值。 The value is assigned twice. 该值分配了两次。 So, why is not the last assigned value displayed in the browser? 那么,为什么最后分配的值没有显示在浏览器中?

Actually the last item is selected, the last item you have added to it's ListItemCollection , the order of selected items doesn't matter obviously. 实际上,最后一项选中,您添加到它的最后一项 ListItemCollection ,所选项目的顺序显然无关紧要。 I think that is just an implementation detail of the browser which renderes the html. 我认为这只是呈现html的浏览器的实现细节。 If you reverse the order of your two selected items(or just remove one since two are invalid for a RadioButtonList ) it would be the desired result. 如果您反转两个选定项的顺序(或者仅删除一个,因为两个对RadioButtonList无效),则将是理想的结果。

Here is the generated HTML in firefox, as you can see both items are "checked" but only the last is actually checked: 这是在firefox中生成的HTML,因为您可以看到两个项目都被“选中”,但实际上只有最后一个被选中:

<table id="Status">
    <tr>
        <td><input id="Status_0" type="radio" name="Status" value="Yes" checked="checked" /><label for="Status_0">Yes</label></td>
    </tr><tr>
        <td><input id="Status_1" type="radio" name="Status" value="No" checked="checked" /><label for="Status_1">No</label></td>
    </tr>
</table>

Sidenote : if you want to select ListItems you don't need to exclude items which should not be selected. 旁注 :如果要选择ListItems ,则不需要排除不应选择的项目。

Incorrect if clause: 不正确的if子句:

foreach (ListItem item in control.Items)
{
    if (item.Value.Trim().Equals(selectedValue.Trim()))
    {
        item.Selected = true;
    }
}

The correct code: 正确的代码:

foreach (ListItem item in control.Items)
{
    item.Selected = item.Value.Trim().Equals(selectedValue.Trim());
}

This also deselects the items correctly. 这也会正确取消选择项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM