在嵌套的gridview webforms中进行分页

时间:2015-03-16 16:35:00

标签: c# asp.net gridview webforms

我在嵌套网格视图中进行分页时遇到了一些麻烦。 当我尝试更改页面时,我会遇到一些非常奇怪和意外的行为。有时它会回发但不会实际更改页面,有时它确实会改变页面,但不会像预期的那样,它会弄乱订单,所以你仍然可以从上一页获得一些项目。

我的标记如下:

<asp:GridView 
    ID="grdImages" 
    runat="server"
    AllowPaging="true"
    ShowFooter="true"
    PageSize="5"
    AutoGenerateColumns="false"
    OnPageIndexChanging="grdImages_PageIndexChanging"
    OnRowCancelingEdit="grdImages_RowCancelingEdit"
    OnRowCommand="grdImages_RowCommand"
    OnRowEditing="grdImages_RowEditing"
    OnRowUpdating="grdImages_RowUpdating"
    OnRowDeleting="grdImages_RowDeleting" 
    EmptyDataText="No Data Available at this Time" 
    OnRowDataBound="grdImages_RowDataBound"  
                DataKeyNames="ProductId">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>        


    <Columns>

        <asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
            <ItemTemplate>
                <asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:DropDownList ID="lstAddProdId" runat="server"  AppendDataBoundItems="true" >
                    <asp:ListItem>Select a product</asp:ListItem>
                </asp:DropDownList>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
            <ItemTemplate>
                <asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label> &nbsp;
                <asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
                <asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:FileUpload ID="flupEditMain" runat="server" />
            </EditItemTemplate>
            <FooterTemplate>
                <asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
            <ItemTemplate>
                <asp:GridView ID="grdSupImages" 
                    runat="server" ShowHeader="false" CellPadding="4" 
                    ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" 
                    OnRowEditing="grdSupImages_RowEditing" 
                    OnRowUpdating="grdSupImages_RowUpdating" AllowPaging="true" PageSize="4"
                    OnPageIndexChanging="grdSupImages_PageIndexChanging"  >
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Label ID="imgSupId" runat="server" Text='<%# Eval("ImgId") %>' ></asp:Label>
                                <asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
                            <asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
                            <asp:CheckBox ID="chkSupImages" runat="server" />
                            </EditItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <EditRowStyle BackColor="#999999"></EditRowStyle>

                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>

                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>

                    <PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>

                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>

                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>

                    <SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>

                    <SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>

                    <SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>

                    <SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
                </asp:GridView>

            </ItemTemplate>

            <FooterTemplate>
                <asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
            </FooterTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
                <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
                <br />
                <span onclick="return confirm('Are you sure you want to delete these images?')">
                    <asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
                </span>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                <br />
                <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
            </EditItemTemplate>
            <FooterTemplate>
                <asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>

    <EditRowStyle BackColor="#999999"></EditRowStyle>

    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>

    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>

    <PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>

    <RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>

    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>

    <SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>

    <SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>

    <SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>

    <SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>

我的代码背后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class Admin_ProductManagement_addProdImage : System.Web.UI.Page
{
private string connectionString =
   WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;

private string imageDirectory;

protected void Page_Load(object sender, EventArgs e)
{

    // ensure images are uploaded to the right folder.
    imageDirectory = Path.Combine(
        Request.PhysicalApplicationPath, @"Images\ProductImages");

    if (!this.IsPostBack)
    {
        BindGrid();
    }
}
protected void BindGrid()
{
    // define ado.net objects.       
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    // define sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "DisplayMain";

    try
    {
        con.Open(); // try to open the connection
        DataSet ds = new DataSet(); // Initializes a new instance of the DataSet class
        adapter.Fill(ds, "ProductImages"); // Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names
        grdImages.DataSource = ds;  // sets the gridview datasource
        grdImages.DataBind();       // binds data to gridview
        // find dropdownlist in the footer row of the gridview
        DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
        // call function
        lstProducts(prods);
    }
    catch (Exception err)
    {
        lblGrdImages.Text = "BindGrid error: " + err.Message + err.Source + err.StackTrace;    // display exceptions in label
    }
    finally
    {
        con.Close();    // close connection, even if action was unsuccessful.
    }
}

protected void BindNestedGrid(int product, GridView grd)
{

    // define ado.net objects.
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter adapt = new SqlDataAdapter(cmd);
    // define sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "DisplayExtra";
    cmd.Parameters.Add(new SqlParameter("@ProductId", SqlDbType.Int));
    cmd.Parameters["@ProductId"].Value = product;
    // try to connect, fill dataset and close connection. Also catch exceptions.
    try
    {
        con.Open(); // open the connection.
        DataSet rds = new DataSet();    // initialize a data set.
        adapt.Fill(rds, "ExtraImages"); // fills dataset
        grd.DataSource = rds;   // assign data source.
        grd.DataBind();     // bind data.
    }
    catch (Exception err)
    {
        lblGrdImages.Text = "Bind Nested Grid Error: " + err.Message;        // catch exceptions.

    }
    finally
    {
        con.Close(); // close the db connection
    }
}

protected void lstProducts(DropDownList prods)
{

    // define ado.net objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataReader reader;
    // define the sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "LstProds";

    try
    {
        con.Open(); // try to connect to db.
        reader = cmd.ExecuteReader();   // execut the reader
        while (reader.Read())
        {                
            ListItem item = new ListItem(); // create listitem
            item.Text = reader["ProductName"].ToString();   // add product name to item text
            item.Value = reader["ProductId"].ToString();    // add productId to item value
            prods.Items.Add(item);    // populate dropdown list.
        }

    }
    catch (Exception err)
    {
        lblGrdImages.Text = "List Products Error: " + err.Message; // display error message in  a label
    }
    finally
    {
        con.Close();    // close the connection.
    }
}
protected void addMain(int ProdId, string ImgName, string ImgPath)
{
    // define ado.net objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    // define sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "AddMain";
    cmd.Parameters.Add(new SqlParameter("@ImageName", SqlDbType.VarChar, 50));
    cmd.Parameters["@ImageName"].Value = ImgName;
    cmd.Parameters.Add(new SqlParameter("@ImagePath", SqlDbType.VarChar, -1));
    cmd.Parameters["@ImagePath"].Value = ImgPath;
    cmd.Parameters.Add(new SqlParameter("@ProductId", SqlDbType.Int));
    cmd.Parameters["@ProductId"].Value = ProdId;

    try
    {
        con.Open(); // attempt to open the connection
        DataSet ds = new DataSet(); // initialize the dataset
        adapter.Fill(ds, "ProductImages");  // fill the data set.           
    }
    catch (Exception err)
    {
        lblGrdImages.Text = "Add main error: " + err.Message;    // display exceptions in a label control
    }
    finally
    {
        con.Close();    // close connection.
    }
}
protected void addExtraImages(int ProductId, string ExImgName, string ExImagePath)
{
    // define ado.net objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    // define sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "AddExtra";
    cmd.Parameters.Add(new SqlParameter("@ProductId", SqlDbType.Int));
    cmd.Parameters["@ProductId"].Value = ProductId;
    cmd.Parameters.Add(new SqlParameter("@ImageName", SqlDbType.VarChar,50));
    cmd.Parameters["@ImageName"].Value = ExImgName;
    cmd.Parameters.Add(new SqlParameter("@ImagePath", SqlDbType.VarChar,-1));
    cmd.Parameters["@ImagePath"].Value = ExImagePath;

    try
    {
        con.Open(); // try to open db connection
        DataSet ds = new DataSet(); // initialize data set.
        adapter.Fill(ds, "ProductImages"); // fill the data set.
    }
    catch (Exception err)
    {
        lblGrdImages.Text = "Add extra images error: " + err.Message;    // display exception in a label
    }
    finally
    {
        con.Close();    // close the connection
    }
}
protected void DeleteProductImages(int Product)
{
    // define ado.net objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    // define sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "Delete";
    cmd.Parameters.Add(new SqlParameter("@ProductId", SqlDbType.Int));
    cmd.Parameters["@ProductId"].Value = Product;

    try
    {
        con.Open(); // open connection
        DataSet ds = new DataSet(); // initialize rthe dataset
        adapter.Fill(ds);   // fill dataset.
    }
    catch (Exception err)
    {
        lblGrdImages.Text = "Delete error:  " + err.Message;        // report error in a label.
    }
    finally
    {
        con.Close();    // close the connection.
    }
}
protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grdImages.PageIndex = e.NewPageIndex;      // sets the page index
    BindGrid();     // bind the grid.
}
protected void grdImages_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    grdImages.EditIndex = -1;   // sets the page index
    BindGrid();         // bind the grid.
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext) // checks extension
{
    bool isValid = false;
    for (int i = 0; i < extAry.Length; i++)
    {
        if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)

            isValid = true;

    }
    return isValid;

}
protected void uploadMainImage() {
    string[] validFileTypes = { ".jpg", ".png" };   // file type array
    FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");  // find control
    DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");  // find control
    string mainFile = Path.GetFileName(main.PostedFile.FileName);                // get file name.
            string ext = Path.GetExtension(mainFile);       // get file extension.
            if (isValid(main.PostedFile, validFileTypes, ext))  // check if file extension is valid.
            {
                if (File.Exists(mainFile))  // check if file exists
                {
                    lblGrdImages.Text = "File with the name: " + mainFile + " already exists. Please rename or choose a different file.";
                }
                else
                {

                    try
                    {
                        string serverFileName = Path.GetFileName(mainFile); // assign values to variables
                        string uploadPath = Path.Combine(imageDirectory, serverFileName);
                        int Product = Convert.ToInt32(products.SelectedValue);
                        main.SaveAs(uploadPath);    // save file
                        addMain(Product, serverFileName, @"~\Images\ProductImages\" + serverFileName);   // Call stored procedure
                    }
                    catch (Exception err)
                    {
                        lblGrdImages.Text = err.Message;
                    }

                }
}
}
protected void uploadExtraImages()
{
    string[] validFileTypes = { ".jpg", ".png" };   // file type array
    FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");    // find conrol
    DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");  // find control
    if (extra.HasFiles)
    {
        foreach (HttpPostedFile file in extra.PostedFiles)
        {
            string ext = Path.GetExtension(file.FileName);
            if (isValid(file, validFileTypes, ext))  // check file extension
            {
                string serverFileName = Path.GetFileName(file.FileName); // assign values to variables
                string uploadPath = Path.Combine(imageDirectory, serverFileName);
                int Product = Convert.ToInt32(products.SelectedValue);
                try
                {
                    file.SaveAs(uploadPath); // save file
                    addExtraImages(Product, serverFileName, @"~\Images\ProductImages\" + serverFileName);  // call stored procedure
                }
                catch (Exception err)
                {
                    lblGrdImages.Text = "Error: " + err.Message;
                }

            }
        }
    }
}
protected void grdImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("Add"))
    {
        // find the required controls in the grdview.            
        FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");
        FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");

        if (main.HasFile)
        {
            uploadMainImage();
            if (extra.HasFiles)
            {
                uploadExtraImages();
            }

            grdImages.EditIndex = -1;
        BindGrid();

        }
        else 
        {
            lblGrdImages.Text = "Product main image is required.";
        }

    }
}
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (!this.IsPostBack)
    {      

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
            Label prodId = (Label)e.Row.FindControl("lblProdId");
            int product = Convert.ToInt32(prodId.Text);        // assign values to variables.
            BindNestedGrid(product, grd);      // call the function.
        }
     }
}


protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    //  find controls
    Label product = (Label)grdImages.Rows[e.RowIndex].FindControl("lblProdId");
    Label image = (Label)grdImages.Rows[e.RowIndex].FindControl("lblMainImgName");
    GridView grd = (GridView)grdImages.Rows[e.RowIndex].FindControl("grdSupImages");
    // declare variables and assign values
    int prodid = Convert.ToInt32(product.Text);
    string path = Server.MapPath(@"~\Images\ProductImages\" + image.Text);
    File.Delete(path);
    foreach(GridViewRow row in grd.Rows)
    {
        Label img = (Label)row.FindControl("imgSupName");
        string imgName = img.Text;
        string imgPath = Server.MapPath(@"~\Images\ProductImages\" + imgName);
        try
        {
            File.Delete(imgPath);

        }
        catch (Exception err)
        {
            lblGrdImages.Text = "File Delete Error:  " + err.Message + "<br />" + err.InnerException + "||" + err.StackTrace;
        }
    }
    DeleteProductImages(prodid);
    grdImages.EditIndex = -1;
    BindGrid();
}



protected void grdImages_RowEditing(object sender, GridViewEditEventArgs e)
{
    grdImages.EditIndex = e.NewEditIndex;

    BindGrid();
}
protected void grdImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

}
protected void grdSupImages_RowEditing(object sender, GridViewEditEventArgs e)
{

}
protected void grdSupImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView gv = (GridView)sender;
    gv.PageIndex = e.NewPageIndex;



}
}

我会永远感谢对此事的任何帮助。如果您需要任何进一步的信息,请告诉我,我会提供。

1 个答案:

答案 0 :(得分:2)

虽然没有人想帮助我,但我找到了问题的答案。 我认为id可以分享这些信息,因为它可以帮助其他人。

这是我为我的孩子gridview pageindexchanging事件提出的:

protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

    GridView gv = (GridView)sender;               
    gv.PageIndex = e.NewPageIndex;        
    BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);


}