gridview 单元格单击编辑

说起这个东东可是耗费了我不少心思,先上个代码
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 从第一个单元格内获得LinkButton控件
                LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
                // 返回一个字符串,表示对包含目标控件的 ID 和事件参数的回发函数的 JavaScript 调用
                string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");

                // 给每一个可编辑的单元格增加事件
                for (int columnIndex = _firstEditCellIndex; columnIndex < e.Row.Cells.Count; columnIndex++)
                {
                    // 增加列索引作为事件参数
                    string js = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString());
                    // 给单元格增加onclick事件
                    e.Row.Cells[columnIndex].Attributes["onclick"] = js;
                    // 给单元格增加鼠标经过时指针样式
                    e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";
                }
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridView _gridView = (GridView)sender;

            switch (e.CommandName)
            {
                case ("SingleClick"):
                    // 获得行索引
                    int _rowIndex = int.Parse(e.CommandArgument.ToString());
                    // 解析事件参数(在RowDataBound中增加的),从而获得被选中的列的索引
                    int _columnIndex = int.Parse(Request.Form["__EVENTARGUMENT"]);
                    // 设置GridView被选中的行的索引(每次回发后判断GridView1.SelectedIndex > -1则更新)
                    _gridView.SelectedIndex = _rowIndex;
                    // 绑定
                    _gridView.DataBind();

                    // 事件记录
                    //this.Message.Text += "单击GridView的行的索引为:" + _rowIndex.ToString()
                    //    + ";列索引为:" + _columnIndex + "<br />";

                    // 获得被选中单元格的显示控件并设置其不可见
                    Control _displayControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[1];
                    _displayControl.Visible = false;
                    // 获得被选中单元格的编辑控件并设置其可见
                    Control _editControl = _gridView.Rows[_rowIndex].Cells[_columnIndex].Controls[3];
                    _editControl.Visible = true;
                    // 清除被选中单元格属性以删除click事件
                    _gridView.Rows[_rowIndex].Cells[_columnIndex].Attributes.Clear();

                    // 设置焦点到被选中的编辑控件
                    ClientScript.RegisterStartupScript(GetType(), "SetFocus",
                        "<script>document.getElementById('" + _editControl.ClientID + "').focus();</script>");
                    // 如果编辑控件是DropDownList的话,那么把SelectedValue设置为显示控件的值
                    if (_editControl is DropDownList && _displayControl is Label)
                    {
                        ((DropDownList)_editControl).SelectedValue = ((Label)_displayControl).Text;
                    }
                    // 如果编辑控件是TextBox的话则选中文本框内文本
                    if (_editControl is TextBox)
                    {
                        ((TextBox)_editControl).Attributes.Add("onfocus", "this.select()");
                    }

                    break;
            }
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //GridView _gridView = (GridView)sender;
            
            string key = "";
            string value = "";

            // NewValues集合里的key
            string[] _columnKeys = new string[] { "Project_id", "Project_name", "Type", "Collect_fees_manner", "Price", "Calculate_Unit", "Calculate_manner", "Cycle", "ZhiNaJin", "Begintime", "Endtime", "Effectivity", "paid", "use_parent_std", "Remarks"};

            if (e.RowIndex > -1)
            {
                // 循环每一列
                for (int i = _firstEditCellIndex; i < GridView1.Columns.Count; i++)
                {
                    // 获得单元格里的控件
                    
                    Control _displayControl = GridView1.Rows[e.RowIndex].Cells[i].Controls[1];
                    
                    Control _editControl = GridView1.Rows[e.RowIndex].Cells[i].Controls[3];
                    

                    // 获得列的key
                    key = _columnKeys[i - _firstEditCellIndex + 1];

                    // 如果单元格处于编辑模式的话,那么从编辑控件中获取值
                    if (_editControl.Visible)
                    {
                        if (_editControl is TextBox)
                        {
                            value = ((TextBox)_editControl).Text;
                        }
                        else if (_editControl is DropDownList)
                        {
                            value = ((DropDownList)_editControl).SelectedValue;
                        }

                        // 增加key/value对到NewValues集合
                        e.NewValues.Add(key, value);
                    }
                    // 否则从显示控件中获取值
                    else
                    {
                        value = ((Label)_displayControl).Text.ToString();

                        // 增加key/value对到NewValues集合
                        e.NewValues.Add(key, value);
                    }
                }
            }
        }
这里面是3个绑定事件分别是rowdatabound、rowcommand、rowupdating,再写个注册动态脚本
 // 注册动态创建的客户端脚本
        protected override void Render(HtmlTextWriter writer)
        {
            // 在RowDataBound中创建的自定义事件必须要在页中注册
            // 通过重写Render方法来调用ClientScriptManager.RegisterForEventValidation。
            // 通过GridViewRow.UniqueID返回行的唯一ID,按纽的唯一ID通过在行的唯一ID后附加“$ct100”而生成。
            foreach (GridViewRow r in GridView1.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    for (int columnIndex = _firstEditCellIndex; columnIndex < r.Cells.Count; columnIndex++)
                    {
                        Page.ClientScript.RegisterForEventValidation(r.UniqueID + "$ctl00", columnIndex.ToString());
                    }
                }
            }

            base.Render(writer);
        }
加个
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.GridView1.DataBind();
               
            }

            if (this.GridView1.SelectedIndex > -1)
            {
                // 调用GridView的UpdateRow方法
                this.GridView1.UpdateRow(this.GridView1.SelectedIndex, false);
                
            }
        }

差点忘了个全局变量:private const int _firstEditCellIndex = 2;

然后后台的话就加个用编辑模板在那里加个itemtemplate里面放一个label加个textbox,记得吧textbox的visual属性设置成false就行了。

完成以后一直有个数据类型转换失败,弄到我吐血,经过调试后发现了问题

//这里的key是指存放到数据库里的位置,它是多减了1如果不加回去的话,你用了不同
的数据的时候就会出现类型转换不正确的错误,经过调试才发现了这个错误
原本的: key = _columnKeys[i - _firstEditCellIndex];
改进的: key = _columnKeys[i - _firstEditCellIndex + 1];

基本上就没什么差错了,对了还要提醒一下配置数据源的时候代码的要跟数据库里面的字段相对应,不然也有你好受的。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值