GridView学习 

RowDataBound事件

在创建gridView控件时,必须先为GridView的每一行创建一个GridViewRow对象,创建每一行时,将引发一个RowCreated事件;当行创建完毕,每一行GridViewRow就要绑定数据源中的数据,当绑定完成后,将引发RowDataBound事件。如果说我们可以利用RowCreated事件来控制每一行绑定的控件,那么我们同样可以利用RowDataBound事件来控制每一行绑定的数据,也就是让数据如何呈现给大家。

还举同样的例子,在数据表中,存在性别列,上面我们用DropListDown控件的DataBounding来表示出了中文的性别,但是毕竟不太美观,我们现在可以利用Label控件和RowDataBound事件来实现完美的中文性别显示。RowDataBound,

首先,还是把性别列,设置为模板列,并添加一个Label控件,将Label控件绑定到数据源的性别段,然后我们在GridView控件属性的事件列表中双击RowDataBound,生成如下事件:

Example:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

//判断当前行是否是数据行

        if (e.Row.RowType == DataControlRowType.DataRow)

        {  //用FindControl方法找到模板中的Label控件

Label lb1= (Label)e.Row.FindControl("Label1");

//因为RowDataBound是发生在数据绑定之后,所以我们可以

//判断Label绑定的数据,如果是True,就更改其text属性为男

                if (lb1.Text== "True")

                      lb1.Text = "男";

                else

                      lb1.Text = "female";

        }

    }

 

3、RowType

RowType可以确定GridView中行的类型,RowType是玫举变量DataControlRowType中的一个值。RowType可以取值包括 DataRow、Footer、Header、EmptyDataRow、Pager、Separator。很多时候,我们需要判断当前是否是数据行,通过如下代码来进行判断 :

   if (e.Row.RowType == DataControlRowType.DataRow)

 

4、RowDeleting和RowDeleted事件

RowDeleting发生在删除数据之前,RowDeleted发生在删除数据之后。

使用RowDeleting事件,可以在真正删除前再次确认是否删除,可以通过设置GridViewDeleteEventArgs.Cancel=True来取消删除;也可以用于判断当前数据库记录数,如果只剩一条记录且数据库不能为空则提示并取消删除操作。

使用RowDeleted事件,可以在删除后,通过GridViewDeletedEventArgs的Exception属性判断删除过程中是否产生异常,如无异常,则可以显示类似于” 1 Records deleted” 之类的提示信息。

Example:

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

//取得当前行号,并取得当前行的GridViewRow对象

        int index=e.RowIndex ;

        GridViewRow gvr=GridView1.Rows[index];

//取得当前行第二个单元格中的文字

        str1 = gvr.Cells[1].Text;

//进行提示

        Message.Text  ="您将删除一个用户,其姓名为"+str1 ;

    }

    protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)

{

//如果没有产生异常,则提示成功删除,否则提示删除失败

        if (e.Exception == null)

            Message.Text += "<br>您成功删除了"+str1 ;

        else

            Message.Text += "删除失败,请联系管理员";

}

5、RowEditing事件

在GridView中的行进入编辑模式之前,引发RowEditing事件,如果您需要在编辑记录前进行某些预处理,可以在这里操作。如果想取消对当前行的编辑,可以把GridViewEditEventArgs 对象的 Cancel 属性设置为 true即可。

Example:

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

//用NewEidIndex取得当前编辑的行号,然后获取gridviewrow对象

        GridViewRow gvr = GridView1.Rows[e.NewEditIndex];

 

//判断,如果当前编辑行姓名栏为admin用户,则取消对当前行的编辑

        if (gvr.Cells[1].Text =="admin")

            e.Cancel = true;

}

 

6、RowUpdating和RowUpdated事件

RowUpdating事件发生在更新数据源之前,RowUpdated发生在更新数据源之后。

我们可以在记录更新前利用RowUpdating做一些预处理工作,比如修改密码时,因为密码在数据库中不是明文存储,进行了hash,所以在更新密码前,应该生成其hash值,再进行更新操作。RowUpdated则可以检验更新是否成功。

Example:

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        GridViewRow gvr = GridView1.Rows[GridView1 .EditIndex  ];

//寻找输入密码的控件

        TextBox tb1 = (TextBox)gvr.FindControl("tb_password");

//将此控件中的文本hash后,把password存入NewValues这个字典中

        e.NewValues ["password"] =tb1.Text .GetHashCode().ToString () ;

 

    }

    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)

{

//如无异常,则更新成功

        if (e.Exception == null)

            Message.Text += "更新成功!";

    }

 

7、Keys、OldValues、NewValues集合

Keys字典中一般存放的是数据源中的主键字段的key和value的对应值,如果主键由多个字段组成,那么Keys为每个键字段添加其字段名称和值。OldValues中存放的是要更新的行的字段名和原始值,每个字段为其中的一项。NewValues中存放的是要更新的行的字段名和修改后的值,每个字段为其中的一项。注意,主键字段只存放于keys集合中。

这三个集合中的每一项都是DictionaryEntry类型的对象,我们可以用DictionaryEntry.Key来确定一个项的字段名称,用DictionaryEntry.Value来确定某项的值。

在上面的例子中,为了把密码明文加密后再存入数据库,我们利用了NewValues字段,重新设置key为password的项的值。为了保证安全性,我们在更新数据前对NewValues中的所有值进行html编码:

 Example1:

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

//遍历NewValues,取得其中每一对DictionaryEntry对象

       foreach (DictionaryEntry de in e.NewValues)

 

//de.key就是字段名,如果此处单独更新某字段的话,也可以直接填写字段名,//比如 e.NewValues[“password”]

 

       e.NewValues[de.Key] = Server.HtmlEncode(de.Value.ToString());

    }

 

Example2:

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

//分别利用Keys、OldValues、NewValues取得主键名、原始数据和更新后数据

        Message .Text  = e.Keys["username"] + "的email地址从" + e.OldValues["email"] + "变更为" + e.NewValues["email"];

}

 

     

    (二)GridView根据值的变化改变行列样式

    我看到论坛中有询问关于如何在GridView随某行某列值的改变时(这些值是空的或不是空的或是其它某些值等),其背景色及文本颜色也随之改变。这篇文章便论述这个问题。

      根据某列的值改变其样式最好的方法是在GridView的DataRowBound事件中想办法。在GridView中的行绑定数据后将立即执行DataRowBound事件。DataRowBound事件使用GridViewRowEventargs类作为事件变量。通过事件变量你能够利用GridViewRowEventArgs属性操作已经绑定数据的行。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

     

    {

     GridViewRow row = e.Row;

    }

      Row将返回TableRow类中的一个GridViewRow对象。

      绑定的Row有几种不同的类型。例如:DataRow, EmptyDataRow, Footer, Header, Pager 和 Separator。通过GridView的RowType属性可以得到当前行的行类型。RowType是一组DataControlRow枚举。

      看下面的代码示例,检测GridView列出的行是否为一个标准类型的行。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

     

    {

     if (e.Row.RowType == DataControlRowType.DataRow)

     {

      //Do something!

     }

    }

      可以使用Row的Cells属性得到其Cells,它将返回一个TableCellCollection对象。然后通过TableCellCollection索引得到特定的Cells。TableCellcollection索引将返回一个TabelCell对象,对应于Row中的一个Cell:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

     

    {

     if (e.Row.RowType == DataControlRowType.DataRow)

     {

      string value = e.Row.Cells[0].Text;

     }

    }

      现在你已经明白了如何得到GridView中某行某列的值,那么根据值的变化改变其样式就比较容易了。以下示例使用 Northwind 数据库,通过检测第四列(UnitPrice)的值是否大于10将其颜色改变为红色。

    <%@ Page Language="C#"%>

     

    <%@ Import Namespace="System.Drawing" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <script runat="server">

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

     if (e.Row.RowType == DataControlRowType.DataRow)

     {

      if (Decimal.Parse(e.Row.Cells[3].Text) > 10)

       e.Row.Cells[3].BackColor = Color.Red;

     }

    }

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

    <title>Untitled Page</title>

    </head>

    <body>

     <form id="form1" runat="server">

     <div>

      <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False"

    DataKeyNames="ProductID" OnRowDataBound="GridView1_RowDataBound">

      <Columns>

       <asp:BoundField ReadOnly="True" HeaderText="ProductID" InsertVisible="False" DataField="ProductID"

    SortExpression="ProductID" />

       <asp:BoundField HeaderText="ProductName" DataField="ProductName" SortExpression="ProductName" />

       <asp:BoundField HeaderText="QuantityPerUnit" DataField="QuantityPerUnit" SortExpression="QuantityPerUnit" />

       <asp:BoundField HeaderText="UnitPrice" DataField="UnitPrice" SortExpression="UnitPrice" />

      </Columns>

     </asp:GridView>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice] FROM [Alphabetical list of products]"

    ConnectionString="<%$ ConnectionStrings:AppConnectionString1 %>" />

    </div>

    </form>

    </body>

    </html>

    (三)Asp.net(C#)写的GridView更新代码

     

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

             {

                 try

                 {

                     string userid = GridView1.DataKeys[e.RowIndex].Value.ToString();//获取主键

                     GridViewRow myrow = GridView1.Rows[e.RowIndex];

                     string name = ((TextBox)myrow.Cells[1].Controls[0]).Text;//获取选中行单元格数据

                     string pwd = ((TextBox)myrow.Cells[2].Controls[0]).Text;

                     string sql = ”update dc4_user_def set username=’” + name + ”‘,password=’” + pwd + ”‘where userid=’” + userid + ”‘”;

                     DBHelper.ExcuteQuery(sql);

                     GridView1.EditIndex = -1;

                     this.BindGridView();                

                 }

                 catch (Exception ex)

                 {

                     Response.Write(ex.Message);

                 }

             }

    些都有了还是一样啊 …………………………
    //响应Gridview控件的分页显示换页事件
    //
    //
    //该事件不一定能够实现,如不能则改过之
    protected void gv_StudentInfoManage_Page(object sender, GridViewPageEventArgs e)
    {
    //实现数据的分页显示
    gv_StudentInfoManage.PageIndex = e.NewPageIndex;
    Bindgrid();
    }




    //响应GridView控件从浏览状态向编辑状态转换处理过程
    protected void gv_StudentInfoManage_RowEditing(object sender, GridViewEditEventArgs e)
    {
    gv_StudentInfoManage.EditIndex = (int)e.NewEditIndex;
    Bindgrid();
    }


    //响应GridView控件取消编辑操作事件
    //
    protected void gv_StudentInfoManage_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
    gv_StudentInfoManage.EditIndex = -1;
    Bindgrid();
    }




    //响应GridView控件的更新事件
    //
    //对页面显示数据进行更新同时使后台数据库中
    //对应的数据表也实现更新
    //保持数据库和页面数据同步
    protected void gv_StudentInfoManage_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    foreach (DictionaryEntry entry in e.NewValues)
    {

    e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());

    }

    }




    //响应GridView控件的删除事件RowDeleting
    //
    //
    protected void gv_StudentInfoManage_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
    //实现行的删除过程
    if (gv_StudentInfoManage.Rows.Count < 1)
    {
    e.Cancel = true;
    this.lbl_Message.Text = "你必须保留最后一条记录,以后才能构浏览和更改!";
    }
    else
    {
    //实现删除操作的具体过程
    //并实实现对删除操作过程的异常处理
    string StrSql = "delete from StudentsInfo where studentID=@userID";
    SqlCommand Cmm = new SqlCommand(StrSql, Conn);
    Cmm.Parameters.Add(new SqlParameter("@userID", SqlDbType.Char, 12));
    Cmm.Parameters["@userID"].Value = gv_StudentInfoManage.DataKeys.ToString();//DataKeys[(int)e.Item.ItemIndex];
    Cmm.Connection.Open();
    try
    {
    Cmm.ExecuteNonQuery();
    lbl_Message.Text = "删除成功!";
    }
    catch (SqlException)
    {
    lbl_Message.Text = "删除失败!";
    lbl_Message.Style["color"] = "red";
    }
    Cmm.Connection.Close();
    Bindgrid();
    }
    }




    //响应GridView控件的删除事件,实现学生信息删除功能
    protected void gv_StudentInfoManage_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {


    //删除的处理过程
    //如果出现异常则抛出,并提示用户改操作失败
    if (e.Exception == null)
    {
    //没有异常抛出,则删除成功
    this.lbl_Message.Text = "删除成功!";
    }
    else {
    this.lbl_Message.Text = "出现异常,删除操作失败!";
    e.ExceptionHandled = true;
    }

    }



    //响应精确查询学生信息按钮控件单击事件
    protected void btn_QueryStudents_Click(object sender, EventArgs e)
    {
    //构建SQL语句,查询符合一定条件的学生的信息
    string StrSql = "select * from StudentsInfo where studentID='" + txt_QueryStudentID + "' or studentName='" + txt_QueryStudentName + "'";

    //当输入查询条件并单击查询按钮时,屏蔽GrideView控件使其不可见
    //同时将符合查询条件的信息显示在表里

    //this.GridView1.Visible = false;

    //创建SqlDataAdapter对象
    SqlDataAdapter da = new SqlDataAdapter(StrSql,Conn);
    //创建DataSet对象,同时填充
    DataSet ds = new DataSet();
    da.Fill(ds);
    gv_StudentInfoManage.DataSource = ds;
    gv_StudentInfoManage.DataBind();

    posted @ 2009-05-01 12:02  不帅你砍我  阅读(214)  评论(0)    收藏  举报