asp.net中有关gridview控件添加编辑按钮的示例(一)

微软为.net中的gridview添加了编辑,删除等处理事件,可是我们想要自己添加这些功能,下面我来介绍一下编辑按钮的示例,我用的是VS2008:

在gridview控件中的列编辑框中添加一列textbox的模板,命名为txt1,:编辑,更新,取消,命令列,首先它是系统生成的东西,当我们选中它时,在右则属性栏中其类型为Link,将其ButtonType调整为Button,并将其转化为TemplateField,然后为gridview控件添加Rowediting事件,并添加如下处理代码:

代码
GridView2.EditIndex = e.NewEditIndex;
        
//当前编辑行背景色高亮
        this.GridView2.EditRowStyle.BackColor =  Color.FromName("#F7CE90");
        
string strSQL = "";
        strSQL 
= "select * from userliuyan ";
        
try
        {
            GridView2.DataSource 
= ws.GetWritersBig(strSQL, CommandType.Text, null);
            GridView2.DataBind();
        }
        
catch (Exception)
        {

            
throw;
        }

 

添加更新事件:

代码
string ID = GridView2.DataKeys[e.RowIndex].Values[0].ToString();
        
string answer = ((TextBox)GridView2.Rows[e.RowIndex].FindControl("txt1")).Text;
        
    
//判断表单项是否有空并给出提示信息
        if (answer == "" &&answer.Length>500)
        {
            Response.Write(
"<script>alert('请输入完整信息!')</script>");
            
return;
        }
        
string sqltxt = "update userliuyan set lAnswer='" + answer + "' where lId=" + ID;
        
int id = 0;
      
//把文本框中的内容更新到数据库不写了

       
if (id != 0)
       {
           Response.Write(
"<script language='javascript'>alert('数据已被保存!');</script>");
           
//返回浏览状态
           string strSQL = "";
           strSQL 
= "select * from userliuyan ";
           
try
           {
               GridView2.DataSource 
= ws.GetWritersBig(strSQL, CommandType.Text, null);
               GridView2.DataBind();
           }
           
catch (Exception)
           {

               
throw;
           }
       }

 

这样一个简单的编辑功能就完成了

posted @ 2009-12-21 22:58  古史漫谈  阅读(3759)  评论(0编辑  收藏  举报