Gridview控件的使用要点

摘要:
在使用Gridview时,您需要记住以下几点:1。如何在表删除和更新等操作中关联数据库的主键。如果有学生信息表,则有以下字段:studID--学生ID,studNo--学生编号,studName--姓名,studSex--性别,studScore--分数。其中,studID是表的主键。有两种方法可以在Gridview中设置和获取表的主键。方法1:使用Gridview的Edit列中的字段

在Gridview的使用中,需要记住的几点:

1、在表格的删除、更新等操作中,如何关联数据库的主键。

  如有一学生信息表:有如下几个字段:studID--学生ID,studNo--学号,studName--姓名,studSex--性别,studScore--成绩。其中,studID为表的主键。

下面有两种方法,使Gridview设置和获取表的主键。

方法一:

  使用Gridview的“编辑列”中的“字段”对话框,由CommandField生成的“删除”按钮,见下面的代码:

<asp:CommandField ShowDeleteButton="True" />

Girdview前台部分页面代码如下:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" onpageindexchanging="GridView1_PageIndexChanging"
onrowdatabound="GridView1_RowDataBound" PageSize="5" Width="657px"
onrowdeleting="GridView1_RowDeleting"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand">
<PagerSettings FirstPageText="第一页" LastPageText="最后页" Mode="NextPrevious"
NextPageText="下一页" PreviousPageText="上一页" />
  <Columns>
   <asp:BoundField DataField="studNo" HeaderText="学号" />
   <asp:BoundField DataField="studName" HeaderText="姓名" />
   <asp:BoundField DataField="studSex" HeaderText="性别" />
   <asp:BoundField DataField="studScore" HeaderText="成绩" />
   <asp:CommandField ShowDeleteButton="True" />
   <asp:CommandField ShowEditButton="True" />
  </Columns>
<PagerStyle HorizontalAlign="Right" />
<HeaderStyle BackColor="#339966" />
</asp:GridView>
 
后台代码如下:
public partial class gridviewTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DBind();
        }
    }

    下面的DBind()函数中利用Gridview的DataKeyNames属性绑定到数据表的主键。为下面进行“删除、插入、更新”等操作提供主键支持。
protected void DBind()
{ SqlConnection con
= dbcon.createConn(); //连接数据库类 con.Open(); SqlDataAdapter sda = new SqlDataAdapter("select * from stud", con); DataSet ds = new DataSet(); sda.Fill(ds, "stud"); this.GridView1.DataKeyNames = new string[] { "studID" }; //为删除、插入、更新等操作提供主键。 this.GridView1.DataSource = ds.Tables["stud"]; this.GridView1.DataBind(); con.Close(); }
    //实现翻页功能    
   protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        DBind();
    }
 在Gridview中实现删除操作。其中:下面一行是获取表中主键的代码:
 int studid = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value); 


//实现表中记录的删除操作

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
        SqlConnection con = dbcon.createConn();
        try
        {
            int studid = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value);
            con.Open();

            SqlCommand cmd = new SqlCommand("delete from stud where studID=" + studid, con);
            cmd.ExecuteNonQuery();
            DBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
  }
  //实现表中记录的“编辑”操作。
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
 {
        this.GridView1.EditIndex = e.NewEditIndex;
        DBind();
 }
  //实现表中记录的“更新”操作。

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //此处同样首先要获取主键。
  }

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { this.GridView1.EditIndex = -1; DBind(); }

}

方法二:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
            AutoGenerateColumns="False" onpageindexchanging="GridView1_PageIndexChanging" 
            onrowdatabound="GridView1_RowDataBound" PageSize="5" Width="657px" 
            onrowdeleting="GridView1_RowDeleting" 
            onrowcancelingedit="GridView1_RowCancelingEdit" 
            onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" 
            onrowcommand="GridView1_RowCommand">
            <PagerSettings FirstPageText="第一页" LastPageText="最后页" Mode="NextPrevious" 
                NextPageText="下一页" PreviousPageText="上一页" />
            <Columns>
                <asp:BoundField DataField="studNo" HeaderText="学号" />
                <asp:BoundField DataField="studName" HeaderText="姓名" />
                <asp:BoundField DataField="studSex" HeaderText="性别" />
                <asp:BoundField DataField="studScore" HeaderText="成绩" />
                            
                <asp:CommandField ShowEditButton="True" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" 
                            CommandArgument='<%# Eval("studID") %>' CommandName="delete">删除记录
               </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <PagerStyle HorizontalAlign="Right" />
            <HeaderStyle BackColor="#339966" />
        </asp:GridView>

前台代码与上面基本相同,只有如下一段区别,这样可提供与表关联主键的另一种方法:

<ItemTemplate>
      <asp:LinkButton ID="LinkButton1" runat="server" 
          CommandArgument='<%# Eval("studID") %>' CommandName="delete">删除记录
   </asp:LinkButton>
</ItemTemplate>

为后台代码提供主键绑定。

  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "delete")
        {   
       //获取表中记录主键的方法
            int stid = Convert.ToInt32(e.CommandArgument);

            //下面省略删除数据表记录的代码。
        }
    }

2、为Gridview中为表格的行和单元格内的控件添加相关的属性,用于实现:1)鼠标在记录行上移动变色,2)在删除表中记录操作前,提供用户进行”确认“。

//在对行进行了绑定后就激发。
//当鼠标在数据行上移动时,行变色
//为删除按钮添加“确认”功能。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
      {
             
          e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor; this.style.backgroundColor='#0088FF';");
          e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c;");

          //为删除按钮添加”确认”功能。 下面的判断是必须的,否则会出现index索引超出范围的错误。
          if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
          {
               //((LinkButton)(e.Row.Cells[4].Controls[0])).Attributes.Add("onclick", "return confirm('真的要删除该用户?');");
               ((LinkButton)(e.Row.Cells[4].Controls[0])).Attributes.Add("onclick", "return confirm('真的要删除该用户?" + DataBinder.Eval(e.Row.DataItem, "studName") + "');");
          }
       }
 }

免责声明:文章转载自《Gridview控件的使用要点》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇rabbitMq实战使用kafka入门下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

NLog类库使用探索——详解配置

https://www.cnblogs.com/fuchongjundream/p/3936431.html 1 配置文件的位置(Configuration file locations)     通过在启动的时候对一些常用目录的扫描,NLog会尝试使用找到的配置信息进行自动的自我配置。 1.1 单独的*.exe客户端     单独的客户端,NLog将在以...

DELPHI移动端支付宝支付

Delphi XE7 Android 应用接入支付宝SDK的方法     1      应用场景和准备工作: 采用XE系列开发的android apps。 apps中需要集成支付宝的支付能力。 支付到指定的商家(一般就是软件开发商自己啦),商家需要事先在支付宝的开放平台申请开通【支付宝无线快捷支付】,具体请百度。 开通【无线快捷支付】后,支付宝应该返回给...

js动态设置根元素的rem方案

方案需求: rem 单位在做移动端的h5开发的时候是最经常使用的单位。为解决自适应的问题,我们需要动态的给文档的根节点添加font-size 值。 使用mediaquery 可以解决这个问题,但是每一个文件都引用一大串的font-size 值很繁琐,而且值也不能达到连续的效果。 就使用js动态计算给文档的fopnt-size 动态赋值解决问题。 设计稿以7...

AndroidManifest.xml文件详解(uses-feature)

http://blog.csdn.net/think_soft/article/details/7596796 语法(SYNTAX): <uses-featureandroid:name="string"              android:required=["true" | "false"]               android:gl...

thinkphp 验证码

在控制器中定义一个控制器,一定要开启 session class PublicAction extends Action {    public function verify()    {        session('[start]');        import('ORG.Util.Image');        Image::buildImag...

C#笔记25:比较和排序(IComparable和IComparer以及它们的泛型实现)

C#笔记25:比较和排序(IComparable和IComparer以及它们的泛型实现) 本文摘要: 1:比较和排序的概念; 2:IComparable和IComparer; 3:IComparable和IComparer的泛型实现IComparable<T>和IComparer<T>; 1:比较和排序的概念     比较:两个实体...