Add RadioButton to ASP. NET GridView,

Source: Internet
Author: User

Add RadioButton to ASP. NET GridView,

One problem encountered during development today is that when a template column containing RadioButton is added to the GridView, the result is a line ..... Oh, my God. You can select multiple single-choice buttons! Sorry! To demonstrate my current error, I want to simulate a functional scenario. The function I want to implement is to display a list of student information containing the single-choice button, select a row and display the details ~!

1. Problem display

① First, prepare a GridView to display the basic information of the student and the most important radio button. The Code is as follows:

<Asp: GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "false"> <Columns> <asp: TemplateField> <ItemTemplate> <asp: radioButton ID = "rbStudent" runat = "server"/> </ItemTemplate> </asp: TemplateField> <asp: boundField DataField = "SName" HeaderText = "username"/> <asp: BoundField DataField = "SSex" HeaderText = "gender"/> </Columns> </asp: GridView>

② Prepare the entity to bind data. The Code is as follows:

public class Student  {    public string SID { get; set; }    public string SName { get; set; }    public string SSex { get; set; }  }

③ Initialize the data and bind the GridView list. The Code is as follows:

Protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {this. bindGridView () ;}} public void BindGridView () {List <Student> sList = new List <Student> () {new Student () {SID = "s001 ", SName = "Zhang San", SSex = "male"}, new Student () {SID = "s002", SName = "Li Si", SSex = "female "}, new Student () {SID = "s003", SName = "", SSex = "male" }}; GridView1.DataSource = sList; GridView1.DataBind ();}

At this time, it seems that there is no problem, but I did find that the single queue has lost its role,

Why? Careful people may say that RadioButton is not a group because you have not set the GroupName attribute, but it still does not work after I set this attribute!

2. Solution

① Problem Analysis

After running, I right-click the source code and find this strange problem. It turns out that the GridView will automatically assign values to the name attribute of input, resulting in different name attributes for each row, the code generated by the GridView is as follows:

<Table cellspacing = "0" rules = "all" border = "1" id = "GridView1" style = "border-collapse: collapse; "> <tr> <th scope =" col "> </th> <th scope =" col "> User Name </th> <th scope =" col "> gender </th> </tr> <td> <input id = "GridView1_rbStudent_0" type = "radio" name = "GridView1 $ ctl02 $ rbStudent" value = "rbStudent "/> </td> <td> zhangsan </td> <td> male </td> </tr> <td> <input id = "GridView1_rbStudent_1" type = "radio" name = "GridView1 $ ctl03 $ rbStudent" value = "rbStudent"/> </td> <td> Li Si </td> <td> female </td> </tr> <td> <input id = "GridView1_rbStudent_2" type = "radio" name = "GridView1 $ ctl04 $ rbStudent" value = "rbStudent"/> </td> <td> Wang Wu </td> <td> male </td> </tr> </table>

We can find that the name attributes of each RadioButton control are different, which leads to the problem that one cannot be selected. How can we solve this problem?

The first way I thought of was to manually change the name attribute to uniform. How can I change it? Some people may say that this is very simple. When using the OnRowDataBound event of the GridView to bind a row, change the name attribute of RadioButton! The Code is as follows:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)    {      if (e.Row.RowType == DataControlRowType.DataRow)      {        RadioButton RadioButtionRB = (RadioButton)e.Row.FindControl("rbStudent");        RadioButtionRB.Attributes["name"] = "student";      }    }

But after the operation, I was disappointed again. Why? This is because RadioButton has a <SPAN> flag outside of the client output, and the name attribute is added to the SPAN, and the crash ends. The evidence is as follows:

<Span name = "student"> <input id = "GridView1_rbStudent_0" type = "radio" name = "GridView1 $ ctl02 $ rbStudent" value = "rbStudent"/> </span> </td> <td> zhangsan </td> <td> male </td> </tr> <td> <span name = "student"> <input id = "GridView1_rbStudent_1" type = "radio" name = "GridView1 $ ctl03 $ rbStudent" value = "rbStudent"/> </span> </td> <td> Li Si </ td> <td> female </td> </tr> <td> <span name = "student"> <input id = "GridView1_rbStudent_2" type = "radio" name = "GridView1 $ ctl04 $ rbStudent" value = "rbStudent"/> </span> </td> <td> Wang Wu </td> <td> male </td>

It seems that this idea is not feasible. We can only use JS. So the question is: after data binding, I decided to use JS to traverse RadioButton IN THE GridView and change the name attribute to the same value. Does it work? Try it!
② Problem Solving
First, implement a JS function to retrieve RadioButton in the GridView and set its name attribute to a uniform value, such as "myradio". The Code is as follows:

<Script type = "text/javascript"> function SetRadioName () {var gv = document. getElementById ("GridView1"); // obtain the Client ID of the GridView var myradio = gv. getElementsByTagName ("input"); // obtain the Inputhtml for (var I = 0; I <myradio. length; I ++) {if (myradio [I]. type = 'Radio ') // hidden {myradio [I]. setAttribute ("name", "myradio") ;}}</script>

Next, register and call the script after binding the data, or write the script to the bottom of the page tag view. The Code is as follows:

 protected void Page_Load(object sender, EventArgs e)    {      if (!IsPostBack)      {        this.BindGridView();        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),          "SetRadioName()", true);      }    }

Problem solved!

After some hard work, the problem is finally solved perfectly, and the entire problem is clearly analyzed. I hope to help my friends solve similar problems and have good ideas. You are welcome to discuss them together.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.