简体   繁体   中英

How to use radio button inside ASP.Net GridView

I want to dipslay in a Gridview with radiobutton list the current date when I run the project. I don't know if the best way is to use JavaScript or C# (I'm using it on Code Behind) and how to do it. If is need to show some code, say it. The grid is filled with a sql statement. The image below shows how I want the grid. Thank you

在此处输入图片说明

Unfortunately, you cannot use RadioButton.GroupName Property in GridView.

Easiest way is to place RadioButton in TemplateField , and use jQuery to manipulate it.

在此处输入图片说明

ASPX

<asp:GridView runat="server" ID="GridView1">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:RadioButton runat="server" ID="MyRadioButton"
                    CssClass="myRadioButton"
                    onclick='<%# "myRadioButtonClick(this)" %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<script type="text/JavaScript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
    function myRadioButtonClick(sender) {
        $('.myRadioButton input').attr('checked', false);
        $(sender).attr('checked', true);
    }
</script>

Code Behind

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    GridView1.DataSource = new List<Customer>
    {
        new Customer {Id = 1, Name = "John"},
        new Customer {Id = 2, Name = "Marry"},
    };
    GridView1.DataBind();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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