GridView的常用操作(增删改查)

void BindData()
        {
            string sql = "select top 10 ID,jobno,jobfixno,jobtype from jobse";
            SqlDataAdapter myda = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            myda.Fill(ds, "RusTable");
            GridView1.DataSource = ds.Tables["RusTable"].DefaultView;
            GridView1.DataBind();
            conn.Close();
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;(GridViewRow     row=GridView1.Rows[e.NewEditIndex])……………………………………………………………………BindData();
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindData();
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox001");
            string dkvalue = GridView1.DataKeys[e.RowIndex].Value.ToString();
            string sql1 = "update jobse set jobno='" + tb.Text.ToString() + "' where id='" + dkvalue + "'";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql1, conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            GridView1.EditIndex = -1;
            BindData();
        }

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

GridViewRow row = GridView1.Rows[e.RowIndex];
…………………………………………………………

BindData()

        }

       protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow row = GridView1.SelectedRow;
…………………………………………………………


四、自定义列中的数据更新

假设数据库中有一个"权限"字段,值为0代表未审核用户,为1代表一般用户,为9则代表管理员用户。根据前面所说的自定义列的办法,通过对DropListDown的绑定,在网页中显示权限为 "管理员",而不是显示数字9。问题产生了,如果我们调整用户权限的话,比如把一般用户更改为管理员,在编辑模版中的用户权限的下拉列表,如何把它的值返回给数据源来完成更新操作。

我们在EditItemTemplate中设置的DropListDown控件,必须选中了Two Way DataBinding,也就是数据双向帮定,这样才能返回数据。前面我们谈到,在GridView中,事件不是单个的,是两个,一个是发生前,一个是发生后,因为我们需要在数据更新前把下拉列表的权限值传送出去,所以我们需要对GridView1_RowUpdating 进行编码,编码如下:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

//当前编辑的是哪行?

             int index = GridView1.EditIndex;


//取得当前编辑行的GridViewRow对象

             GridViewRow gvr = GridView1.Rows[index];


//在当前行中,寻找DropListDown控件

             DropDownList dp = (DropDownList)gvr.FindControl("editdrop");


//将DropListDown的值赋给NewValues集合中的权限字段。

             e.NewValues["rights"] = dp.SelectedValue;

}


2、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"];

posted @ 2008-07-28 22:03  PointNet  阅读(9629)  评论(0编辑  收藏  举报