在GridView中添加Radiobutton

GridView中增加选择项来作为RadioButton的替代项

   1:  <asp:GridView ID="grv" runat="server" AutoGenerateColumns="False" >
   2:   
   3:       <Columns>
   4:   
   5:            <asp:CommandField ShowSelectButton="True" HeaderText="选择" />
   6:   
   7:       </Columns>
   8:   
   9:  </asp:GridView>

数据绑定时重新将选择项的LinkButton的值显示成RadioButton

   1:  protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
   2:  {
   3:   
   4:       if (e.Row.RowType == DataControlRowType.DataRow)
   5:      {
   6:   
   7:            LinkButton lb = (LinkButton)e.Row.Cells[0].Controls[0];
   8:            lb.Text = "<div><input type=\"radio\" name=\"myRadio\" 
                     onclick=\"Javascript:__doPostBack   
   9:                  ('grv','Select¥" + e.Row.RowIndex + "')\"></div>";
  10:       }
  11:   
  12:  } 

这样就能通过GridView的选择事件来得到当前选中行,但选择事件执行就会PostBack页面,单选按钮的选中状态会被重置。需要设置一下:

   1:  protected void grv_SelectedIndexChanged(object sender, EventArgs e)
   2:  {
   3:   
   4:       LinkButton lb = (LinkButton)grv.Rows[grv.SelectedIndex].Cells[0].Controls[0];
   5:   
   6:       lb.Text = "<div><input type=\"radio\" name=\"myRadio\" 
                  onclick=\"Javascript:__doPostBack(\"grv \",
   7:           \"Select¥" + grv.SelectedIndex + "\" )\" checked=\"checked\"></div>";
   8:   
   9:  } 

这个事件中我们将选中行的LinkButton的值重新再赋值,当然是赋个选中状态的Radio了,不过到这里还是不算完美,因为当你多选几次记录后,你会发现选中状态永远只在最后一条记录上,我们看看页面的源码就会发现,所有选择过的记录的Radio上都有checked=’checked’,因为只允许同时存在一个选中项,所以永远只有最后被写入的那条记录被选中,这不是你想要的结果吧…… 再来解决这个问题,还好GridView有选择项改变前和改变后事件,刚才我们利用了改变后事件,现在就在改变前做做文章了

   1:  protected void grv_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
   2:  {
   3:   
   4:       if (grv.SelectedIndex > -1)
   5:      {
   6:            LinkButton lb = (LinkButton)grv.Rows[grv.SelectedIndex].Cells[0].Controls[0];
   7:   
   8:            lb.Text = "<div><input type=\"radio\" name=\"myRadio\" 
                              onclick=\"javascript:__doPostBack
   9:               ('grv','Select¥" + grv.SelectedIndex + "' )\"></div>";
  10:   
  11:       }
  12:   
  13:  } 

到此就大功告成了!假如想要页面不闪,那就上ajax吧~

转载自:CrazyCoder

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>