GridView实现双击进行编辑,更新

虽然标题是原创,但是其实主要的思想呢还是接见了晓风残月的思路,今天在晓风残月的博客上看到了如何利用GridView来实现双击进行编辑。我决定动手实现一下,由于还没有实现双击进行更改操作,所以顺便就把这个功能加了上去,希望对大家能有帮助,同时也谢谢晓风残月。

效果图如下:

前台代码

 

         < asp:GridView  ID ="GridView1"  runat ="server"  AutoGenerateColumns ="False"  BackColor ="White"
            BorderColor
="#CCCCCC"  BorderStyle ="None"  BorderWidth ="1px"  CellPadding ="3"  OnRowEditing ="GridView1_RowEditing"  OnRowDataBound ="GridView1_RowDataBound"  OnRowUpdating ="GridView1_RowUpdating"  OnRowCommand ="GridView1_RowCommand" >
            
< FooterStyle  BackColor ="White"  ForeColor ="#000066"   />
            
< Columns >
                
< asp:ButtonField  Text ="SingleClick"  CommandName ="SingleClick"  Visible ="false"  ButtonType ="Link" />
                
< asp:TemplateField  HeaderText ="ID" >
                    
< ItemTemplate >
                        
<% Eval("customerid") %>
                    
</ ItemTemplate >
                    
< EditItemTemplate >
                        
< asp:TextBox  ID ="ID"  runat  ="server"  Text ='<%#  Bind("customerid")% > '> </ asp:TextBox >
                    
</ EditItemTemplate >
                
</ asp:TemplateField >
                
< asp:TemplateField  HeaderText ="CompanyName" >
                    
< ItemTemplate >
                        
<% Eval("CompanyName") %>
                    
</ ItemTemplate >
                    
< EditItemTemplate >
                        
< asp:TextBox  ID ="CName"  runat  ="server"  Text ='<%#  Bind("CompanyName")% > '> </ asp:TextBox >
                    
</ EditItemTemplate >
                
</ asp:TemplateField >
                
< asp:TemplateField  HeaderText ="ContactName" >
                    
< ItemTemplate >
                        
<% Eval("ContactName") %>
                    
</ ItemTemplate >
                    
< EditItemTemplate >
                         
< asp:TextBox  ID ="Name"  runat  ="server"  Text ='<%#  Bind("ContactName")% > '> </ asp:TextBox >
                    
</ EditItemTemplate >
                
</ asp:TemplateField >
                
< asp:TemplateField  HeaderText ="Address" >
                    
< ItemTemplate >
                        
<% Eval("Address") %>
                    
</ ItemTemplate >
                    
< EditItemTemplate >
                        
< asp:TextBox  ID ="Address"  runat  ="server"  Text ='<%#  Bind("Address")% > '> </ asp:TextBox >
                    
</ EditItemTemplate >
                
</ asp:TemplateField >
            
</ Columns >
            
< RowStyle  ForeColor ="#000066"   />
            
< SelectedRowStyle  BackColor ="#669999"  Font-Bold ="True"  ForeColor ="White"   />
            
< PagerStyle  BackColor ="White"  ForeColor ="#000066"  HorizontalAlign ="Left"   />
            
< HeaderStyle  BackColor ="#006699"  Font-Bold ="True"  ForeColor ="White"   />
        
</ asp:GridView >
    
    
</ div >
    
</ form >

 

后台代码

 

     string  ConStr  =  ConfigurationManager.ConnectionStrings[ " NorthwindConnectionString " ].ConnectionString;
    
protected   void  Page_Load( object  sender, EventArgs e)
    
{
        
if (!IsPostBack)
        
{
            BindData();
        }

    }



    
private   void  BindData()
    
{

        SqlConnection MyCon 
= new SqlConnection(ConStr);
        
string QueryStr = "SELECT customerid,CompanyName,ContactName,Address FROM customers";
        SqlDataAdapter Da 
= new SqlDataAdapter(QueryStr, MyCon);
        DataSet Ds 
= new DataSet();
        Da.Fill(Ds, 
"Customers");
        GridView1.DataSource 
= Ds.Tables[0];
        GridView1.DataKeyNames 
= new string[] "customerid" };
        GridView1.DataBind();

    }


    
protected   override   void  Render(HtmlTextWriter writer)
    
{
        
foreach (GridViewRow Row in GridView1.Rows)
        
{
            
if (Row.RowType == DataControlRowType.DataRow)
            
{
                
//双击进入编辑模式
                Row.Attributes["ondblclick"= ClientScript.GetPostBackEventReference(GridView1, "Edit$" + Row.RowIndex.ToString(), true);
                Row.Attributes[
"style"= "cursor:pointer";
                Row.Attributes[
"title"= "双击进入编辑";
                
if (Row.RowState == DataControlRowState.Edit)
                
{
                    Row.Attributes.Remove(
"ondblclick");
                    Row.Attributes.Remove(
"style");
                    Row.Attributes[
"title"= "编辑行";
                    
for (Int32 i = 1; i < GridView1.Columns.Count; i++)
                    
{
                        ((TextBox)Row.Cells[i].Controls[
1]).Attributes.Add("onmouseover""this.select()");

                    }

                    
//双击更新
                    Row.Attributes["ondblclick"= ClientScript.GetPostBackEventReference(GridView1, "Update$" + Row.RowIndex.ToString(), true);

                }

                
//
                for (int i = 1; i < Row.Cells.Count; i++)
                
{
                    Page.ClientScript.RegisterForEventValidation(Row.UniqueID 
+ "$ctl00", i.ToString());
                }

            }

        }

        
base.Render(writer);
    }



    
protected   void  GridView1_RowEditing( object  sender, GridViewEditEventArgs e)
    
{
        GridView1.EditIndex 
= e.NewEditIndex;
        BindData();
    }



    
protected   void  GridView1_RowUpdating( object  sender, GridViewUpdateEventArgs e)
    
{
        
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
        
//防止非法的输入,预防脚本攻击
        string CustomerId = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[1]).Text.ToString());
        
string CompanyName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[1]).Text.ToString());
        
string ContactName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[1]).Text.ToString());
        
string Address = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[1]).Text.ToString());
        SqlConnection Con 
= new SqlConnection(ConStr);
        
string UpdateStr = "UPDATE customers SET companyname=@CompanyName,contactname=@ContactName,address=@Address  WHERE customerid=@ID";
        
//插入数据的时候用参数来可以预防SQL注入攻击,提高系统的安全性
        SqlCommand UpdateCmd = new SqlCommand(UpdateStr,Con);
        SqlParameter ParmID 
= new SqlParameter("@ID", SqlDbType.NVarChar,20);
        ParmID.Value 
= ID;
        SqlParameter ParmCName 
= new SqlParameter("@CompanyName", SqlDbType.NVarChar, 20);
        ParmCName.Value 
= CompanyName;
        SqlParameter ParmName 
= new SqlParameter("@ContactName",SqlDbType.NVarChar,20);
        ParmName.Value 
= ContactName;
        SqlParameter ParmAddr 
= new SqlParameter("@Address",SqlDbType.NVarChar,20);
        ParmAddr.Value 
= Address;
        
try
        
{
            UpdateCmd.Parameters.Add(ParmCName);
            UpdateCmd.Parameters.Add(ParmName);
            UpdateCmd.Parameters.Add(ParmAddr);
            UpdateCmd.Parameters.Add(ParmID);
            Con.Open();
            UpdateCmd.ExecuteNonQuery();
            Con.Close();
        }

        
catch
        
{
            ShowMessage(
"输入格式不正确,请检查");
        }

        
finally
        
{
            Con.Close();
            GridView1.EditIndex 
= -1;
            BindData();
        }

    }


    
private   void  ShowMessage( string  Message)
    
{
        Literal TxtMsg 
= new Literal();
        TxtMsg.Text 
= "<script>alert('" + Message + "')</script>";
        Page.Controls.Add(TxtMsg);
    }



    
protected   void  GridView1_RowDataBound( object  sender, GridViewRowEventArgs e)
    
{

    }

    
protected   void  GridView1_RowCommand( object  sender, GridViewCommandEventArgs e)
    
{
        GridView ControlGridView 
= (GridView)sender;
        
if (e.CommandName == "SingleClick")
        
{
            
int RowIndex = int.Parse(e.CommandArgument.ToString());
            
int ColIndex = int.Parse(Request.Form["__EVENTARGUMENT"]);
            Response.Write(
"<script>alert('你点击了第"+(RowIndex+1)+"行的第"+(ColIndex)+"列');</script>");

        }

    }

}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值