datagrid分页后删除最后一页的最后一条记录后会出错,我用以下的代码来判断也还是不行,会出现删除当前页会跳到前一页(不管是不是最后一页)的错误。删除事件:
  If MyDataGrid.CurrentPageIndex < (Me.MyDataGrid.PageCount And MyDataGrid.CurrentPageIndex <> 0) Then  '判断            MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
        
  End If
        OpenDataBase_BindToDataGrid()

解决方案 »

  1.   

    If (MyDataGrid.CurrentPageIndex < Me.MyDataGrid.PageCount-1 And MyDataGrid.CurrentPageIndex <> 0) Then  '判断            MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
            
      End If
            OpenDataBase_BindToDataGrid()
      

  2.   

    上面错了;应该是
    If (MyDataGrid.CurrentPageIndex >= Me.MyDataGrid.PageCount-1 and MyDataGrid.CurrentPageIndex <> 0) Then  '判断            MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
            
      End If
            OpenDataBase_BindToDataGrid()
      

  3.   

    if(datagrid.Items.Count==1&&datagrid.CurrentPageIndex>0)
    {
    datagrid.CurrentPageIndex--;
    }
      

  4.   

    if(MyDataGrid.Items.Count==0 && MyDataGrid.CurrentPageIndex!=0)
    {
       MyDataGrid.CurrentPageIndex-=1;
    }
      

  5.   

    还有一种方法就是在删除前做判断;
    if(e.Item.ItemIndex==0 and MyDataGrid.Items.Count==1)
    MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1;
    if(MyDataGrid.CurrentPageIndex<0)
    MyDataGrid.CurrentPageIndex=0;
      

  6.   

    <form id="Form1" method="post" runat="server">
    <asp:datagrid id="dgOrder" runat="server" Height="515px" Width="718px" AutoGenerateColumns="False" AllowSorting="True" CellPadding="4" BorderWidth="1px" BorderColor="#A0ABEB" PageSize="15" BorderStyle="Solid" BackColor="White" GridLines="Vertical" ForeColor="Black" AllowPaging="True" ShowFooter="True">
    <SelectedItemStyle ForeColor="White" BackColor="Black"></SelectedItemStyle>
    <AlternatingItemStyle BackColor="#EEEEEE"></AlternatingItemStyle>
    <HeaderStyle HorizontalAlign="Center" ForeColor="White" BorderColor="#6876C5" BackColor="#6876C5"></HeaderStyle>
    <FooterStyle ForeColor="White" BackColor="#6876C5"></FooterStyle>
    <Columns>
    <asp:TemplateColumn>
    <ItemTemplate>
    <FONT face="">
    <asp:CheckBox id="Cb" runat="server"></asp:CheckBox></FONT>
    </ItemTemplate>
    </asp:TemplateColumn>
    <asp:BoundColumn DataField="orderid" SortExpression="orderid" HeaderText="ID">
    <HeaderStyle Width="180px"></HeaderStyle>
    </asp:BoundColumn>
    <asp:BoundColumn DataField="ShipCountry" SortExpression="ShipCountry" HeaderText="ShipCountry">
    <HeaderStyle Width="180px"></HeaderStyle>
    </asp:BoundColumn>
    <asp:BoundColumn DataField="ShippedDate" SortExpression="ShippedDate" HeaderText="ShippedDate" DataFormatString="{0:d}">
    <HeaderStyle Width="180px"></HeaderStyle>
    </asp:BoundColumn>
    <asp:BoundColumn DataField="Freight" SortExpression="Freight" HeaderText="Freight">
    <HeaderStyle Width="180px"></HeaderStyle>
    </asp:BoundColumn>
    <asp:BoundColumn DataField="ShipAddress" SortExpression="ShipAddress" HeaderText="ShipAddress">
    <HeaderStyle Width="480px"></HeaderStyle>
    </asp:BoundColumn>
    </Columns>
    <PagerStyle HorizontalAlign="Center" ForeColor="Black" Position="TopAndBottom" BackColor="White" Mode="NumericPages"></PagerStyle>
    </asp:datagrid>
    </form>
      

  7.   

    '得到数据视图,参数为要排序的列
    Private Function GetDv(ByVal strSort As String) As DataView
            '定义数据库连接
            Dim dv As DataView
            Dim CN As New SqlConnection()
            Try
                '初始化连接字符串
                CN.ConnectionString = "data source=pmserver;
                initial catalog=Northwind;persist security info=False;user id=sa;Password=sa;"
                CN.Open()
    '从NorthWind得到orders表的数据
                Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from orders", CN)
                Dim ds As New DataSet()
                adp.Fill(ds)
                '得到数据视图
                dv = ds.Tables(0).DefaultView
            Catch ex As Exception
    #If DEBUG Then
                Session("Error") = ex.ToString()
                Response.Redirect("../error.aspx")        '跳转程序的公共错误处理页面
    #End If
            Finally
                '关闭连接
                CN.Close()
            End Try
            '排序
            dv.Sort = strSort
            Return dv
        End Function    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) 
        Handles MyBase.Load
            If Not IsPostBack Then
                ViewState("strSort") = "orderid"
                dgOrder.DataSource = GetDv(ViewState("strSort").ToString())
                dgOrder.DataBind()
            End If
        End Sub
    '排序
        Private Sub dgOrder_SortCommand(ByVal source As Object, 
        ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgOrder.SortCommand
            dgOrder.CurrentPageIndex = 0
       '得到排序的列
            ViewState("strSort") = e.SortExpression.ToString()
            dgOrder.DataSource = GetDv(ViewState("strSort").ToString())
            dgOrder.DataBind()
        End Sub '分页
        Private Sub dgOrder_PageIndexChanged(ByVal source As Object, 
        ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dgOrder.PageIndexChanged
       '得到分页的页号
            dgOrder.CurrentPageIndex = e.NewPageIndex
            dgOrder.DataSource = GetDv(ViewState("strSort").ToString())
            dgOrder.DataBind()
        End Sub 
      

  8.   

    If MyDataGrid.CurrentPageIndex < Me.MyDataGrid.PageCount And MyDataGrid.CurrentPageIndex <> 0 Then  '判断            MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
            
      End If
    把括号去了
      

  9.   

    全部的代码都试过了,都是提示:无效的 CurrentPageIndex 值。它必须大于等于 0 且小于 PageCount。 
      

  10.   

    我已验证了skytear(将进酒)是对的,lin_lin不正确
      

  11.   

    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="AD_edit.aspx.vb" Inherits="ad1.AD_edit"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <title>admin</title>
    <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
    <meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
    <meta content="JavaScript" name="vs_defaultClientScript">
    <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
    <LINK href="css/style.css" type="text/css" rel="stylesheet">
    <script language="javascript">
    function SelectAll()
    {
      var e = event.srcElement;
      var inputs = document.forms[0].elements;
      for (var i=0; i < inputs.length; i++)
        if (inputs[i].type == "checkbox" && inputs[i].name.indexOf("chkMyDataGrid") >=0)
        inputs[i].checked = e.checked;
    }
    </script>
    </HEAD>
    <body>
    <form id="Form1" method="post" runat="server">
    <P><FONT face="宋体"></FONT>&nbsp;</P>
    <asp:datagrid id="MyDataGrid" runat="server" Width="100%" OnPageIndexChanged="ChangePage" AllowPaging="True"
    AutoGenerateColumns="False" DataKeyField="T_ID">
    <SelectedItemStyle Font-Underline="True" BackColor="Gainsboro"></SelectedItemStyle>
    <AlternatingItemStyle BackColor="WhiteSmoke"></AlternatingItemStyle>
    <HeaderStyle Font-Bold="True" HorizontalAlign="Center" BackColor="LightGray"></HeaderStyle>
    <Columns>
    <asp:BoundColumn DataField="t_id" ReadOnly="True" HeaderText="编号">
    <HeaderStyle HorizontalAlign="Center" Width="30px"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    <FooterStyle HorizontalAlign="Center"></FooterStyle>
    </asp:BoundColumn>
    <asp:TemplateColumn HeaderText="删除">
    <HeaderStyle HorizontalAlign="Center" Width="30px" VerticalAlign="Middle"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
    <ItemTemplate>
    <asp:CheckBox id="chkMyDataGrid" runat="server"></asp:CheckBox>
    </ItemTemplate>
    <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle"></FooterStyle>
    </asp:TemplateColumn>
    <asp:HyperLinkColumn Text="查 看" Target="_blank" DataNavigateUrlField="T_FileName" DataNavigateUrlFormatString="ad_img/{0}"
    HeaderText="查看图像">
    <ItemStyle Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
    </asp:HyperLinkColumn>
    <asp:HyperLinkColumn Text="查 看" Target="_blank" DataNavigateUrlField="T_Path" DataNavigateUrlFormatString="{0}"
    HeaderText="广告连接地址">
    <ItemStyle Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
    </asp:HyperLinkColumn>
    <asp:HyperLinkColumn Target="_blank" DataNavigateUrlField="T_ID" DataNavigateUrlFormatString="AD_Edit.aspx?editID={0}"
    DataTextField="T_Say" HeaderText="编辑此广告">
    <HeaderStyle Wrap="False" HorizontalAlign="Center" Width="250px" VerticalAlign="Middle"></HeaderStyle>
    <ItemStyle Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
    <FooterStyle Wrap="False"></FooterStyle>
    </asp:HyperLinkColumn>
    <asp:TemplateColumn HeaderText="起始时间">
    <HeaderStyle Wrap="False" HorizontalAlign="Center"></HeaderStyle>
    <ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
    <ItemTemplate>
    <asp:Label runat="server" Text='<%# forStr.strAgio((DataBinder.Eval(Container, "DataItem.T_Incept"))) %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterStyle Wrap="False" HorizontalAlign="Center"></FooterStyle>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="结束时间">
    <HeaderStyle Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
    <ItemStyle Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
    <ItemTemplate>
    <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.T_Finish") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.T_Finish") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateColumn>
    <asp:BoundColumn DataField="T_place" HeaderText="广告的位置">
    <ItemStyle Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
    </asp:BoundColumn>
    <asp:BoundColumn DataField="T_Validate" HeaderText="验证">
    <ItemStyle Wrap="False" HorizontalAlign="Center" ForeColor="#FF0033" VerticalAlign="Middle"></ItemStyle>
    </asp:BoundColumn>
    </Columns>
    <PagerStyle NextPageText="下一页" PrevPageText="上一页" Mode="NumericPages"></PagerStyle>
    </asp:datagrid>
    <P></FONT><asp:checkbox id="mycheck" onclick="SelectAll()" runat="server" Text="全选/反选"></asp:checkbox><asp:button id="btnDEL" runat="Server" CausesValidation="False" text="确定删除"></asp:button><FONT face="宋体"></FONT></P>
    </form>
    </body>
    </HTML>
      

  12.   

    Imports System.Data.sqlclient
    Imports System.Data
    Public Class AD_edit
        Inherits System.Web.UI.Page#Region " Web 窗体设计器生成的代码 "    '该调用是 Web 窗体设计器所必需的。
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()    End Sub
        Protected WithEvents MyDataGrid As System.Web.UI.WebControls.DataGrid
        Protected WithEvents mycheck As System.Web.UI.WebControls.CheckBox
        Protected WithEvents btnDEL As System.Web.UI.WebControls.Button    '注意: 以下占位符声明是 Web 窗体设计器所必需的。
        '不要删除或移动它。
        Private designerPlaceholderDeclaration As System.Object    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: 此方法调用是 Web 窗体设计器所必需的
            '不要使用代码编辑器修改它。
            InitializeComponent()
        End Sub#End Region
        Public forStr As New forStr    Dim Rd As SqlDataReader
        Dim SQL As String
        Dim Conn As SqlConnection
        Dim mysqlDB = ConfigurationSettings.AppSettings("sqlDB")
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            '在此处放置初始化页的用户代码
            btnDEL.Attributes.Add("onclick", "return confirm('您是否要删除你选中的记录吗?');")
            If Not IsPostBack Then
                OpenDataBase_And_BindToDataGrid()
            End If    End Sub    Sub OpenDataBase_And_BindToDataGrid()
            ' 打开
            Try
                SQL = "Select * From AED_AD Where T_User= '" & strUnite() & "'" & "order by T_REGhour desc"
                MyDataGrid.DataSource = strSQLvb.ExecuteDataset(mysqlDB, CommandType.Text, SQL)
                MyDataGrid.DataBind()        Catch ex As Exception
                Response.Write(ex.Message)
            End Try    End Sub
        Sub ChangePage(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
            '分页
            mycheck.Checked = False
            MyDataGrid.CurrentPageIndex = e.NewPageIndex
            OpenDataBase_And_BindToDataGrid()
        End Sub
        Private Sub btnDEL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDEL.Click
            Try            Conn = New SqlConnection(mysqlDB)
                Conn.Open()            Dim dgi As DataGridItem
                For Each dgi In MyDataGrid.Items
                    Dim cb As CheckBox = CType(dgi.FindControl("chkMyDataGrid"), CheckBox)                If cb.Checked Then                    SQL = "Select * From AED_AD Where T_Validate=1 and T_ID='" & dgi.Cells(0).Text & "'"                    Rd = strSQLvb.ExecuteReader(mysqlDB, CommandType.Text, SQL)                    If Rd.HasRows = True Then
                            Response.Write("删除失败,因为你选中的记录最少有一条已经被管理员确定")
                            Rd.Close()
                            Exit Sub
                        End If
                        Rd.Close()
                        '---------------------------------------
                        SQL = "delete from AED_AD  where  T_ID=" & dgi.Cells(0).Text
                        strSQLvb.ExecuteNonQuery(mysqlDB, CommandType.Text, SQL)                End If
                Next dgi
                Conn.Close()        Catch ex As Exception
                Response.Write(ex.Message)
                Conn.Close()
            End Try        'If (MyDataGrid.CurrentPageIndex < Me.MyDataGrid.PageCount And MyDataGrid.CurrentPageIndex <> 0) Then
            '    MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
            'End If
            If MyDataGrid.Items.Count = 1 And MyDataGrid.CurrentPageIndex > 0 Then
                MyDataGrid.CurrentPageIndex -= 1
            End If
            OpenDataBase_And_BindToDataGrid()
            Me.mycheck.Checked = False    End SubEnd Class
      

  13.   

    以上是全部代码(全选+删除),skytear(将进酒)的方法只有单选有效果,如果全选就没效果了。
      

  14.   


            'If (MyDataGrid.CurrentPageIndex < Me.MyDataGrid.PageCount And MyDataGrid.CurrentPageIndex <> 0) Then
            '    MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
            'End If
            If MyDataGrid.Items.Count = 1 And MyDataGrid.CurrentPageIndex > 0 Then
                MyDataGrid.CurrentPageIndex -= 1
            End If
    注释掉再试试
      

  15.   

    你这种情况,你必须在删除记录后,重新计算记录数和页数等与DataGrid相关的东西,不能用        'If (MyDataGrid.CurrentPageIndex < Me.MyDataGrid.PageCount And MyDataGrid.CurrentPageIndex <> 0) Then
            '    MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
            'End If
            If MyDataGrid.Items.Count = 1 And MyDataGrid.CurrentPageIndex > 0 Then
                MyDataGrid.CurrentPageIndex -= 1
            End If
    来判断
      

  16.   

    其实只要看删除事件就好了。
    Private Sub btnDEL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDEL.Click
            Try            Conn = New SqlConnection(mysqlDB)
                Conn.Open()            Dim dgi As DataGridItem
                For Each dgi In MyDataGrid.Items
                    Dim cb As CheckBox = CType(dgi.FindControl("chkMyDataGrid"), CheckBox)                If cb.Checked Then                    SQL = "Select * From AED_AD Where T_Validate=1 and T_ID='" & dgi.Cells(0).Text & "'"                    Rd = strSQLvb.ExecuteReader(mysqlDB, CommandType.Text, SQL)                    If Rd.HasRows = True Then
                            Response.Write("删除失败,因为你选中的记录最少有一条已经被管理员确定")
                            Rd.Close()
                            Exit Sub
                        End If
                        Rd.Close()
                        '---------------------------------------
                        SQL = "delete from AED_AD  where  T_ID=" & dgi.Cells(0).Text
                        strSQLvb.ExecuteNonQuery(mysqlDB, CommandType.Text, SQL)                End If
                Next dgi
                Conn.Close()        Catch ex As Exception
                Response.Write(ex.Message)
                Conn.Close()
            End Try        'If (MyDataGrid.CurrentPageIndex < Me.MyDataGrid.PageCount And MyDataGrid.CurrentPageIndex <> 0) Then
            '    MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
            'End If
            If MyDataGrid.Items.Count = 1 And MyDataGrid.CurrentPageIndex > 0 Then
                MyDataGrid.CurrentPageIndex -= 1
            End If
            OpenDataBase_And_BindToDataGrid()
            Me.mycheck.Checked = False    End Sub
      

  17.   

    我想了下面的代码没有测试过,你试一下,
    MyDataGrid.CurrentPageIndex = 0 
    OpenDataBase_And_BindToDataGrid()
          If (MyDataGrid.CurrentPageIndex < Me.MyDataGrid.PageCount And MyDataGrid.CurrentPageIndex <> 0) Then
                MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
          End If
          If MyDataGrid.Items.Count = 1 And MyDataGrid.CurrentPageIndex > 0 Then
                MyDataGrid.CurrentPageIndex -= 1
          End If
          Me.mycheck.Checked = False
      

  18.   

    更正一下
    MyDataGrid.CurrentPageIndex = 0 
    OpenDataBase_And_BindToDataGrid()
          If (Me.MyDataGrid.PageCount >0) Then
                MyDataGrid.CurrentPageIndex = MyDataGrid.CurrentPageIndex - 1
          End If
          Me.mycheck.Checked = False
      

  19.   

    不能取datagrid的pagecout,要取你的数据源的:)
      

  20.   

    删除后加下面的判断
    if(this.DataGridName.item.count == 0 && this.DataGridName.Pagecount >1)
    {
      this.DataGridName.CurrentPage -= 1;
    }
      

  21.   

    if(this.DataGrid1.Items.Count==1&&this.DataGrid1.CurrentPageIndex>0)
    {
    this.DataGrid1.CurrentPageIndex-=1;
    }
    databind();
      

  22.   

    判断datagrid.items.count的个数
    如果=1,那么就把DataGridName.CurrentPage = 0 
    跳到第1页算了 :)
    然后邦定
      

  23.   

    我想 : zhangfire(色狼也可以学.net)  说得对,只是不知道怎么写代码///
      

  24.   

    以上的各位写的代码在当前页面只剩下一条记录的时候是可以的,但是在当前页面不只一条记录的时候似乎不行."datagrid.Items.Count==1"用于计算当前页面是否只剩下一条记录,如若一次性删除当前页面中的所有记录则就不行了.