Gridview控件的使用要点

在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") + "');");
          }
       }
 }
原文地址:https://www.cnblogs.com/myindg/p/2860417.html