GridView 双击某一列的单元格可以编辑,其它列不能接受鼠标事件,如何做?希望有具体的ASP.NET的代码,看看。

解决方案 »

  1.   

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" AllowSorting="True" OnRowCommand="GridView1_RowCommand"
            OnRowDataBound="GridView1_RowDataBound" OnRowUpdating="GridView1_RowUpdating">
            <Columns>
                <asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False" />
                <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False"
                    ReadOnly="True" SortExpression="EmployeeID" />
                <asp:TemplateField HeaderText="LastName" SortExpression="LastName">
                    <ItemTemplate>
                        <asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
                        <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' Visible="false"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
                    <ItemTemplate>
                        <asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
                        <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>' Visible="false"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country" SortExpression="Country">
                    <ItemTemplate>
                        <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
                        <asp:DropDownList ID="ddlCountry" runat="server" Visible="False" AutoPostBack="True"
                            DataSourceID="SqlDataSource1" DataTextField="Country" DataValueField="Country">
                        </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                            SelectCommand="SELECT DISTINCT [Country] FROM [Employees]"></asp:SqlDataSource>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        &nbsp;
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            DeleteCommand="DELETE FROM [Employees] WHERE [EmployeeID] = @EmployeeID" InsertCommand="INSERT INTO [Employees] ([LastName], [FirstName], [Country]) VALUES (@LastName, @FirstName, @Country)"
            SelectCommand="SELECT [LastName], [FirstName], [Country], [EmployeeID] FROM [Employees]"
            UpdateCommand="UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Country] = @Country WHERE [EmployeeID] = @EmployeeID">
            <DeleteParameters>
                <asp:Parameter Name="EmployeeID" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="LastName" Type="String" />
                <asp:Parameter Name="FirstName" Type="String" />
                <asp:Parameter Name="Country" Type="String" />
                <asp:Parameter Name="EmployeeID" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="LastName" Type="String" />
                <asp:Parameter Name="FirstName" Type="String" />
                <asp:Parameter Name="Country" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
        <br />
        <br />
        <asp:Label ID="Message" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
      

  2.   

    /*为了方便,我们称Label为显示控件,TextBox或DropDownList为编辑控件*/
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;public partial class Control_EditIndividualCell : System.Web.UI.Page
    {
        private const int _firstEditCellIndex = 2;    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);
            }
        }    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].FindControl("lblLastName");
                    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;
            }
        }    /// <summary>
        /// 把值(values)从EditItemTemplate转移到NewValues集合里(使用数据源控件的话就需要这步)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridView _gridView = (GridView)sender;
            string key = "";
            string value = "";        // NewValues集合里的key
            string[] _columnKeys = new string[] { "LastName", "FirstName", "Country" };        if (e.RowIndex > -1)
            {
                // 循环每一列
                for (int i = _firstEditCellIndex; i < _gridView.Columns.Count; i++)
                {
                    // 获得单元格里的控件
                    Control _displayControl = _gridView.Rows[e.RowIndex].Cells[i].Controls[1];
                    Control _editControl = _gridView.Rows[e.RowIndex].Cells[i].Controls[3];                // 获得列的key
                    key = _columnKeys[i - _firstEditCellIndex];                // 如果单元格处于编辑模式的话,那么从编辑控件中获取值
                    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);
                    }
                }
            }
        }    // 注册动态创建的客户端脚本
        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);
        }
    }
      

  3.   

    “/WebSite1”应用程序中的服务器错误。
    --------------------------------------------------------------------------------指定的参数已超出有效值的范围。
    参数名: index 
    说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.ArgumentOutOfRangeException: 指定的参数已超出有效值的范围。
    参数名: index源错误: 
    行 234:
    行 235:            // 从第一个单元格内获得LinkButton控件 
    行 236:            LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
    行 237:            // 返回一个字符串,表示对包含目标控件的 ID 和事件参数的回发函数的 JavaScript 调用 
    行 238:            string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
     
      

  4.   

    你那代码我在网上也看到了的,我也那样试了的。都是不行的啊firstEditCellIndex这个变量等于 1是不?
    LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
    我昨天弄的也是这个地方出问题了。到底怎么回事了?老是说
    指定的参数已超出有效值的范围。
    参数名: index 
      

  5.   

    页面代码:
                <asp:GridView ID="GridView2" runat="server"  OnPageIndexChanging="GridView2_OnPageIndexChanging"  
                  AutoGenerateColumns="False"  Width="81%" CellPadding="3" GridLines="None" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellSpacing="1" AllowPaging="True" 
                    OnRowEditing="GridView2_RowEditing" OnRowUpdating="GridView2_RowUpdating"  OnRowCancelingEdit="GridView2_RowCancelingEdit" 
                    OnRowDataBound="GVSelect_RowDataBound"  OnRowCommand="GridView2_RowCommand">  
                    <Columns>
                        <asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False" /> 
                        <asp:BoundField DataField="UploadDate" HeaderText="上传日期" HtmlEncode="False"   DataFormatString="{0:yyyy-MM-dd}" >
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField>
              
                        <asp:BoundField DataField="UploadFileName" HeaderText="上传文件名" >
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField>
                        <asp:BoundField DataField="UploadPath" HeaderText="文件路径">
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField> 
                        
                        <asp:TemplateField HeaderText="用户列表"> 
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                            <ItemTemplate> 
                                <asp:Label ID="lblUserList" runat="server" Text=' <%# Eval("UserList") %>'> </asp:Label> 
                                <asp:TextBox ID="txtUserList" runat="server" Text=' <%# Eval("UserList") %>' Visible="false"> </asp:TextBox> 
                            </ItemTemplate> 
                        </asp:TemplateField> 
                        
                      
                        
                        <asp:BoundField DataField="UserList" HeaderText="用户列表">
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField> 
                        <asp:CommandField ShowEditButton="True" HeaderText="编辑用户列表">
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                            <ControlStyle ForeColor="Blue" />
                        </asp:CommandField>
                    </Columns>
                      <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                    <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                    <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                    <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            </asp:GridView> 
      

  6.   

    自己写比较烦人,用现成的控件吧.随便找个grid的控件
      

  7.   

    呵呵,不是绑定的问题。
      // 获得单元格里的控件 
        Control editControl = gridView.Rows[rowIndex].Cells[_firstEditCellIndex].Controls[3];
        string value = ((TextBox)editControl).Text;
    只能这样取值。
    问题解决了哦。累死我了,还有一个小问题就是点击之后怎么会变成紫色的,很奇怪,我也没设置紫色啊。            <asp:GridView ID="GridView2" runat="server"  OnPageIndexChanging="GridView2_OnPageIndexChanging"  
                  AutoGenerateColumns="False"  Width="81%" CellPadding="3" GridLines="None" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellSpacing="1" AllowPaging="True" 
                     OnRowDataBound="GridView2_RowDataBound"  OnRowCommand="GridView2_RowCommand">  
                    <Columns>
                        <asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False" /> 
                        
                        <asp:BoundField DataField="UploadDate" HeaderText="上传日期" HtmlEncode="False"   DataFormatString="{0:yyyy-MM-dd}" >
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField>
              
                        <asp:BoundField DataField="UploadFileName" HeaderText="上传文件名" >
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField>
                        <asp:BoundField DataField="UploadPath" HeaderText="文件路径">
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField> 
                        
                        <asp:TemplateField HeaderText="用户列表"> 
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                            <ItemTemplate> 
                                <asp:Label ID="lblUserList" runat="server" Text=' <%# Eval("UserList") %>'> </asp:Label> 
                                <asp:TextBox ID="txtUserList" runat="server" Text=' <%# Eval("UserList") %>' Visible="false"> </asp:TextBox> 
                            </ItemTemplate> 
                        </asp:TemplateField> 
                        <asp:ButtonField ButtonType="Button"  HeaderText="更新列表" ShowHeader="True" Text="更新"  CommandName="RefreshList" >
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:ButtonField>
                        
                    </Columns>
                      <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                    <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                    <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                    <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            </asp:GridView> 
      

  8.   

    C#代码:
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
        {        if (e.Row.RowType == DataControlRowType.DataRow)
            {            //当鼠标停留时更改背景色            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#8EC26F'");            //当鼠标移开时还原背景色            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");            //设置悬浮鼠标指针形状为"小手"            e.Row.Attributes["style"] = "Cursor:hand";            // 从第一个单元格内获得LinkButton控件 
                LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
                // 返回一个字符串,表示对包含目标控件的 ID 和事件参数的回发函数的 JavaScript 调用 
                string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");            // 给每一个可编辑的单元格增加事件 
               int columnIndex = _firstEditCellIndex; 
                
                // 增加列索引作为事件参数 
                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 GridView2_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();
                    bind2();                // 获得被选中单元格的显示控件并设置其不可见 
                    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 TextBox && _displayControl is Label)
                    {
                        ((TextBox)_editControl).Text = ((Label)_displayControl).Text;
                    }
                    // 如果编辑控件是TextBox的话则选中文本框内文本 
                    if (_editControl is TextBox)
                    {
                        ((TextBox)_editControl).Attributes.Add("onfocus", "this.select()");
                    }                break;            case ("RefreshList"):                GridView gridView = (GridView)sender;                int rowIndex = Convert.ToInt32(e.CommandArgument);
          
                    string value = "";
            
                    // 获得单元格里的控件 
                    Control editControl = gridView.Rows[rowIndex].Cells[_firstEditCellIndex].Controls[3];                // 如果单元格处于编辑模式的话,那么从编辑控件中获取值 
                    if (editControl.Visible)
                    {
                        if (editControl is TextBox)
                        {
                            value = ((TextBox)editControl).Text;                        string sqlstr = "update [UploadFile] set UserList='"
                               + value.Trim()
                               + "' where UploadName='"
                               + GridView2.DataKeys[rowIndex].Value.ToString().Trim() + "' and UploadFileName = '"
                               + GridView2.Rows[rowIndex].Cells[2].Text.ToString().Trim() + "'";
                            sqlcom = new SqlCommand(sqlstr, sqlcon);
                            sqlcon.Open();
                            sqlcom.ExecuteNonQuery();
                            sqlcon.Close();
                            GridView2.EditIndex = -1;
                            bind2();
                        }
                    }                       break;
            }
        }    // 注册动态创建的客户端脚本 
        protected override void Render(HtmlTextWriter writer)
        {
            // 在RowDataBound中创建的自定义事件必须要在页中注册 
            // 通过重写Render方法来调用ClientScriptManager.RegisterForEventValidation。 
            // 通过GridViewRow.UniqueID返回行的唯一ID,按纽的唯一ID通过在行的唯一ID后附加“$ct100”而生成。 
            foreach (GridViewRow r in GridView2.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    int columnIndex = _firstEditCellIndex; 
                    
                    Page.ClientScript.RegisterForEventValidation(r.UniqueID + "$ctl00", columnIndex.ToString());
                    
                }
            }        base.Render(writer);
        } 
      

  9.   

    因为我自己的数据写得比它的还烦datalist里嵌套这个gridview,所以就把他原来的代码发你了!
      

  10.   

       Control _displayControl = _gridView.Rows[_rowIndex].Cells[1].Controls[1];为什么总是报异常: 指定的参数已超出有效值的范围。
    参数名: index