【问题标题】:asp.net create radiobutton from datasetasp.net 从数据集创建单选按钮
【发布时间】:2013-02-17 12:01:57
【问题描述】:

我有一个包含许多项目的数据集,包括“blockID”和“blockName”。 我想填充它们的值将是“blockName”属性的单选按钮列表,并且我需要将它们按“blockID”属性分组。即用户只能从每个“blockID”中选择一个“blockName”。 我正在使用 C# 那可能吗? 感谢您的帮助!

【问题讨论】:

    标签: c# asp.net dataset radio-button


    【解决方案1】:

    是的,这是可能的。我在下面做了一个例子,我知道它不是 DataSet,但仍然是一个很好的例子,说明你如何做到这一点。仍然可以从该结构的 DataSet 进行映射,因为在我看来它确实使事情变得更容易。

    给定 DataSource 项的以下块类:

    public class Block
    {
        public int ID { get; set; }
        public List<string> BlockNames { get; set; }
    
        public Block(int id, params string[] names)
        {
            ID = id;
            BlockNames = new List<string>();
            foreach (var item in names)
            {
                BlockNames.Add(item);
            }
        }
    }
    

    你看,在这个类中,BlockNames 已经与单个块的ID 分组。

    在您的 ASPX/ASCX 标记中,定义 Repeater 并订阅 OnItemDataBound 事件:

    <asp:Repeater ID="rptDummy" runat="server" OnItemDataBound="rptDummy_OnItemDataBound">
    </asp:Repeater>
    

    OnItemDataBound 事件中,动态添加RadioButtonLists,每个BlockName 是不同的RadioButton,每个RadioButtonList 是不同的BlockID:

    protected void rptDummy_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Block blk = (Block)e.Item.DataItem;
            RadioButtonList list = new RadioButtonList();
            list.ID = "rblBlocks";
            list.Attributes.Add("BlockID", blk.ID.ToString());
    
            foreach (string item in blk.BlockNames)
            {
                list.Items.Add(new ListItem(item, item));
            }
    
            e.Item.Controls.Add(list);
        }
    }
    

    绑定中继器:

    List<Block> blocks = new List<Block>();
    
    blocks.Add(new Block(1, "BlockName1", "BlockName2", "BlockName3"));
    blocks.Add(new Block(2, "BlockName4", "BlockName5"));
    blocks.Add(new Block(3, "BlockName6"));
    
    rptDummy.DataSource = blocks;
    rptDummy.DataBind();
    

    【讨论】:

    • 非常感谢您的回复。有一件事我认为我没有很好地解释,我谈到的“块”在数据库中,我们使用一个过程从数据库中获取它。这些程序返回给我们一个数据集。该数据集包含许多“blockID”和“blockName”,我们必须根据“blockID”将它们分成单选按钮组,非常感谢!
    • 是的,我的回答涵盖了许多 BlockID 和许多与之相关的 Blocknames 的场景。我知道您没有我使用的数据结构,但您绝对可以将您拥有的Dataset 转换为使用的Block 对象中的List。正如我所说,它是您想要的一个很好的选择。
    • 好的,我现在看到了!非常感谢!
    猜你喜欢
    • 2011-07-28
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多