现在的位置: 首页 > 综合 > 正文

gridview 中RadioButton 使用

2019年11月19日 ⁄ 综合 ⁄ 共 2330字 ⁄ 字号 评论关闭

本来是想模仿C/S的样子完成单击一列直接触发事件,后来知道那样要用到AJAX,最后还是用了RadioButton这样实现起来相对简单,不过只能在要求不高是时候用。

 使用这个先要在gridview 里放入RadioButton模板。然后激发它的checked事件然后在此事件里可以捕捉到点的那一列,要注意就是点完了要将RadioButton的checked设置为false,这样看不到刚点过的痕迹,不过也算凑合能是些头的任务.....

 protected void OrdersGridView_ClickChanged(object sender, EventArgs e)
   {
       foreach (GridViewRow row in this.OrdersGridView.Rows)
       {
            RadioButton radioButton = (RadioButton)row.FindControl("RadioButton1");
            if (radioButton.Checked)
           {
                //显示从表内容
               int i = Convert.ToInt32(radioButton.Text);
               string sqlstr = "SELECT * FROM [Order Details] where orderID='" + i + "' ORDER BY [OrderID]";
               string TableName = "OrderDetails";
                GridViewBind(sqlstr, TableName, OrderDetailsGridView);

                radioButton.Checked = false;           
            }
        }

 /// <summary>
    /// 根据tablename和sql语句绑定GridView1到数据库
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="tablename"></param>
    /// <param name="GridView1"></param>
    protected void GridViewBind(string sqlstr, string tablename,GridView  GridView1)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, con);
        DataSet ds = new DataSet();
        da.Fill(ds, tablename);
        GridView1.DataSource = ds.Tables[tablename].DefaultView;
        GridView1.DataBind();

    }

下面的代码用脚本实现RadioButton的单选。不过当激活了RadioButton服务器端的checked事件后脚本事件作用被覆盖。

.aspx

//  var last = null;//最后访问的RadioButton的ID
//        function judge(obj)
//        {
//              if(last == null)
//                {
//                    last = obj.id;
//                // alert(last);
//                }
//                else
//                {
//                   var lo = document.getElementById(last);
//                    lo.checked = false;
//                //alert(last + "   " + lo.checked);           
//                    last = obj.name;
//                }
//               obj.checked = "checked";
//               // alert(obj.id-100);
//               }

.cs

    protected void OrdersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
             RadioButton rb = (RadioButton)e.Row.FindControl("RadioButton1");
            rb.Attributes.Add("onclick", "judge(this)");//给RadioButton添加onclick属
        }

    }
 

抱歉!评论已关闭.