关闭

GridView 常用方法合集

563人阅读 评论(0) 收藏 举报
在项目中主要用了gridview来显示数据,其中的方法都是常用的。
1、利用sqldatasource动态邦定数据,其中sqldatasource1是托放在页面的sqldatasource控件,将数据邦定到gridview1上面
    void gridviewband() {
            
try
            {
                SqlDataSource1.ConnectionString 
= ConfigurationSettings.AppSettings[ "sqlconn"];
                SqlDataSource1.SelectCommand 
= squerysql;
                GridView1.DataSource 
= SqlDataSource1;
                GridView1.DataBind();
                
//看有没有数据 如果没有数据 提示错误  lblresult的text的内容是错误信息  
                 int count = GridView1.Rows.Count;
                
if (count == 0) { lblresult.Visible  = true; }
                
else { lblresult.Visible  = false; }
            }
            
catch   (SqlException ex5)
            {
                
//提示错误信息
            }
            
finally {  
            }
    }

2、选择一行,获取关键字,然后传到其他页面
    protected void GridView1_SelectedIndexChanged( object sender, EventArgs e)
    {
//选择某一行
        Session[ "selectkey"= GridView1.SelectedDataKey.Value;
        Response.Redirect(
"~/employee/employeedetail.aspx");
    }

3、获取编辑行的关键字
         protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        
//编辑修改
        Session[ "editkey"= GridView1.DataKeys[e.NewEditIndex].Value.ToString();
        Response.Redirect(
"~/employee/employeeedit.aspx");
    }

4、删除一行,获取关键字。这个地方还是用rowdeleting 事件。
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
       
        String idno111 
= GridView1.DataKeys[e.RowIndex].Value.ToString();
        SqlDataSource1.DeleteCommand 
= "delete from empinfo where empnum=' " + idno111 + "'" 
            
+ "delete from employee where empnum=' " + idno111 + "'";
        
//删除行
         if (e.RowIndex >= 0)
        {

            String connectstr 
= ConfigurationSettings.AppSettings[ "sqlconn"];
            SqlConnection sqlconn 
= new SqlConnection(connectstr);
            sqlconn.Open();
            SqlCommand comm 
= new SqlCommand(SqlDataSource1.DeleteCommand, sqlconn);
            comm.ExecuteNonQuery();
            sqlconn.Close();
        }
    }

5、删除前提示关键字,不仅仅是提示“确认删除吗?” 而是提示“确认删除关键字是***的数据吗?”

首先在aspx文件脚本里面要设置 重要看的是gridview的标签里面要有
 DatakeyNames="关键字" 同时 CommandArgument='<%# Eval("departno") %>'  这两处要填写
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        CellPadding
="4" DataKeyNames="departno" DataSourceID="SqlDataSource1" ForeColor="#333333"
        GridLines
="None" OnDataBound="CustomersGridView_DataBound" OnRowDeleting="GridView1_RowDeleting"
        OnRowEditing
="GridView1_RowEditing" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
        PageSize
="15" Width="800px" OnRowDataBound="GridView1_RowDataBound">
        
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        
<Columns>
            
<asp:BoundField DataField="departno" HeaderText="部门编号" SortExpression="departno" />
            
<asp:BoundField DataField="father" HeaderText="父级部门" SortExpression="father" />
            
<asp:BoundField DataField="departname" HeaderText="部门名称" SortExpression="departname" />
            
<asp:BoundField DataField="person" HeaderText="联系人" SortExpression="person" />
            
<asp:BoundField DataField="tel" HeaderText="固定电话" SortExpression="tel" />
            
<asp:BoundField DataField="mobiletel" HeaderText="手机" SortExpression="mobiletel" />
            
            
<asp:CommandField ButtonType="Image" HeaderText="查看" SelectImageUrl="~/icons/look.gif"
                SelectText
="查看" ShowSelectButton="True">
                
<HeaderStyle HorizontalAlign="Center" />
                
<ItemStyle HorizontalAlign="Center" />
            
</asp:CommandField>
            
<asp:CommandField ButtonType="Image" EditImageUrl="~/icons/edit.gif" EditText="编辑"
                HeaderText
="编辑" ShowEditButton="True">
                
<HeaderStyle HorizontalAlign="Center" />
                
<ItemStyle HorizontalAlign="Center" />
            
</asp:CommandField>
            
<asp:TemplateField HeaderText="删除" ShowHeader="False">
                
<ItemStyle HorizontalAlign="Center" />
                
<HeaderStyle HorizontalAlign="Center" />
                
<ItemTemplate>
                    
<asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False" CommandName="Delete"
                        ImageUrl
="~/icons/delete.gif" CommandArgument='<%# Eval("departno") %>' Text="删除" />
                
</ItemTemplate>
            
</asp:TemplateField>
        
</Columns>
        
        
<PagerTemplate>
            
<table width="100%">
                
<tr>
                    
<td width="70%">
                        
<asp:Label ID="MessageLabel" runat="server" Font-Size="Larger" ForeColor="Black"
                            Text
="页码:"></asp:Label>
                        
<asp:DropDownList ID="PageDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged" >
                        
</asp:DropDownList>
                        
<asp:LinkButton ID="linkBtnFirst" runat="server" CommandArgument="First" CommandName="Page"
                            ForeColor
="Black">首页</asp:LinkButton>
                        
<asp:LinkButton ID="linkBtnPrev" runat="server" CommandArgument="Prev" CommandName="Page"
                            ForeColor
="Black">上一页</asp:LinkButton>
                        
<asp:LinkButton ID="linkBtnNext" runat="server" CommandArgument="Next" CommandName="Page"
                            ForeColor
="Black">下一页</asp:LinkButton>
                        
<asp:LinkButton ID="linkBtnLast" runat="server" CommandArgument="Last" CommandName="Page"
                            ForeColor
="Black">末页</asp:LinkButton>
                    
</td>
                    
<td align="right" width="70%">
                        
<asp:Label ID="CurrentPageLabel" runat="server" ForeColor="black"></asp:Label>
                    
</td>
                
</tr>
            
</table>
        
</PagerTemplate>
        
        
<RowStyle BackColor="#EFF3FB" />
        
<EditRowStyle BackColor="#2461BF" />
        
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        
<AlternatingRowStyle BackColor="White" />
    
</asp:GridView>

然后在cs页面里填入事件:

    //删除某一行的时候要提示关键字  不仅是提示确认删除,departno是关键字
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        
if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton l 
= (ImageButton)e.Row.FindControl( "ImageButton1" );
            l.Attributes.Add(
"onclick""javascript: return " +
            
"confirm('确认要删除部门编号为   " +
            DataBinder.Eval(e.Row.DataItem, 
"departno"+ " 的部门吗?" + "')");
        }
    }
}


这样删除的时候就能提示关键字了。

6、显示页码
显示页码要在aspx代码里填入几行数据,上面的代码已经有了 重新写一下:
代码放在 </Columns>下面

         <PagerTemplate>
            
<table width="100%">
                
<tr>
                    
<td width="70%">
                        
<asp:Label ID="MessageLabel" runat="server" Font-Size="Larger" ForeColor="Black"
                            Text
="页码:"></asp:Label>
                        
<asp:DropDownList ID="PageDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged" >
                        
</asp:DropDownList>
                        
<asp:LinkButton ID="linkBtnFirst" runat="server" CommandArgument="First" CommandName="Page"
                            ForeColor
="Black">首页</asp:LinkButton>
                        
<asp:LinkButton ID="linkBtnPrev" runat="server" CommandArgument="Prev" CommandName="Page"
                            ForeColor
="Black">上一页</asp:LinkButton>
                        
<asp:LinkButton ID="linkBtnNext" runat="server" CommandArgument="Next" CommandName="Page"
                            ForeColor
="Black">下一页</asp:LinkButton>
                        
<asp:LinkButton ID="linkBtnLast" runat="server" CommandArgument="Last" CommandName="Page"
                            ForeColor
="Black">末页</asp:LinkButton>
                    
</td>
                    
<td align="right" width="70%">
                        
<asp:Label ID="CurrentPageLabel" runat="server" ForeColor="black"></asp:Label>
                    
</td>
                
</tr>
            
</table>
        
</PagerTemplate>

然后在gridview的标签里面填入

OnDataBound="CustomersGridView_DataBound"

位置看 5 的代码就可以了。
然后再 cs代码区加入如下代码

//显示页码

    
protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
    {
        GridViewRow pagerRow 
= GridView1.BottomPagerRow;
        DropDownList pageList 
= (DropDownList)pagerRow.Cells[ 0].FindControl("PageDropDownList");
        GridView1.PageIndex 
= pageList.SelectedIndex;
    }

    
protected void CustomersGridView_DataBound(Object sender, EventArgs e)
    {
        
try
        {
            GridViewRow pagerRow 
= GridView1.BottomPagerRow;

            LinkButton linkBtnFirst 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnFirst");
            LinkButton linkBtnPrev 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnPrev");
            LinkButton linkBtnNext 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnNext");
            LinkButton linkBtnLast 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnLast");

            
if (GridView1.PageIndex  == 0)
            {
                linkBtnFirst.Enabled 
= false;
                linkBtnPrev.Enabled 
= false;
            }
            
else if (GridView1.PageIndex  == GridView1.PageCount - 1)
            {
                linkBtnLast.Enabled 
= false;
                linkBtnNext.Enabled 
= false;
            }
            
else if (GridView1.PageCount  <= 0)
            {
                linkBtnFirst.Enabled 
= false;
                linkBtnPrev.Enabled 
= false;
                linkBtnNext.Enabled 
= false;
                linkBtnLast.Enabled 
= false;
            }
            DropDownList pageList 
= (DropDownList)pagerRow.Cells[ 0].FindControl("PageDropDownList");
            Label pageLabel 
= (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");

            
if (pageList != null)
            {
                
for (int i = 0; i < GridView1.PageCount; i ++)
                {
                    
int pageNumber = i + 1;
                    ListItem item 
= new ListItem(pageNumber.ToString()  + "/" + GridView1.PageCount.ToString(), pageNumber.ToString());
                    
if (i == GridView1.PageIndex)
                    {
                        item.Selected 
= true;
                    }
                    pageList.Items.Add(item);
                }
            }
            
if (pageLabel != null)
            {
                
int currentPage = GridView1.PageIndex + 1;
                pageLabel.Text 
= "当前页: " + currentPage.ToString()  +
                  
" / " + GridView1.PageCount.ToString();
            }
        }
        
catch 
        {
            Response.Write(
"现在还没有该部门的记录!!");
        }
    }

如果发生异常,是应为没有数据。这时候可以在catch里面提示没有数据。这样就可以绑定页码了。
但是这样做的条件是没有把绑定数据放在 (!ispostback)里面,如果放在里面了,就会出问题
因为页面的代码实际上是控制显示第几页。但是绑定数据放在了!ispostback里面了,所以不能重新绑定。
这样的情况,要写那个绑定的方法。
然后在cs文件里写下面的代码:

    protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
    {
        GridViewRow pagerRow 
= GridView1.BottomPagerRow;
        DropDownList pageList 
= (DropDownList)pagerRow.Cells[ 0].FindControl("PageDropDownList");
        GridView1.PageIndex 
= pageList.SelectedIndex;
        gridviewband();
///重新绑定数据,这是特殊的地方
    }

    
protected void CustomersGridView_DataBound(Object sender, EventArgs e)
    {
        
try
        {
            GridViewRow pagerRow 
= GridView1.BottomPagerRow;

            LinkButton linkBtnFirst 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnFirst");
            LinkButton linkBtnPrev 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnPrev");
            LinkButton linkBtnNext 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnNext");
            LinkButton linkBtnLast 
= (LinkButton)pagerRow.Cells[ 0].FindControl("linkBtnLast");

            
if (GridView1.PageIndex  == 0)
            {
                linkBtnFirst.Enabled 
= false;
                linkBtnPrev.Enabled 
= false;
            }
            
else if (GridView1.PageIndex  == GridView1.PageCount - 1)
            {
                linkBtnLast.Enabled 
= false;
                linkBtnNext.Enabled 
= false;
            }
            
else if (GridView1.PageCount  <= 0)
            {
                linkBtnFirst.Enabled 
= false;
                linkBtnPrev.Enabled 
= false;
                linkBtnNext.Enabled 
= false;
                linkBtnLast.Enabled 
= false;
            }
            DropDownList pageList 
= (DropDownList)pagerRow.Cells[ 0].FindControl("PageDropDownList");
            Label pageLabel 
= (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");

            
if (pageList != null)
            {
                
for (int i = 0; i < GridView1.PageCount; i ++)
                {
                    
int pageNumber = i + 1;
                    ListItem item 
= new ListItem(pageNumber.ToString()  + "/" + GridView1.PageCount.ToString(), pageNumber.ToString());
                    
if (i == GridView1.PageIndex)
                    {
                        item.Selected 
= true;
                    }
                    pageList.Items.Add(item);
                }
            }
            
if (pageLabel != null)
            {
                
int currentPage = GridView1.PageIndex + 1;
                pageLabel.Text 
= "当前页: " + currentPage.ToString()  +
                  
" / " + GridView1.PageCount.ToString();
            }
        }
        
catch //(Exception ex5)
        {
            Response.Write(
"现在还没有该部门的记录!!");
        }
    }
        
protected void GridView1_PageIndexChanging( object sender, GridViewPageEventArgs e)
    {
        
        GridView1.PageIndex 
= e.NewPageIndex;
        gridviewband();
//重新绑定数据
    }

这样就可以显示了 如果按照前面的方法会提示没有  pageindexchanging事件。 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:170595次
    • 积分:2358
    • 等级:
    • 排名:第16396名
    • 原创:82篇
    • 转载:22篇
    • 译文:0篇
    • 评论:10条
    最新评论