ASP。 NET Gridview 与 DataSourceID 绑定不正确

ASP. NET Gridview with DataSourceID not binding properly

我有一个使用 gridview 的页面,其中声明了 datasourceID,文件显示正确。但是,每当我更新 gridview 的照片时,gridview 都不会正确更新,尽管我的文件夹中的照片已从更新中检索到。我能让他们检索到正确照片的唯一方法是我真的按下 F5 或重新加载项目。 网格视图也在更新面板内。

<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
    <ProgressTemplate>   
        <div class="overlay" align="center">
            <div class="over">
            <img alt="progress" src="images/loader.gif"/>
           Processing...        </div> 
    </div>  
        </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
    <ContentTemplate>
<div id="staffList">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableViewState="false" EnableCaching="false" ConnectionString="<%$ ConnectionStrings:Database1Entities %>"
                SelectCommand="SELECT * FROM (SELECT Staff.[StaffID], Staff.[StaffName], Staff.[PhoneNo], Staff.[Photo], Staff.[EmpmType], Staff.[AcadStaff], Designation.[DesignationName], Section.[SectionName], Groups.[GroupName], Staff.[InternetAddr], ROW_NUMBER() OVER(ORDER BY Designation.[SortingOrder]) AS Rownum FROM Staff LEFT JOIN Designation ON Designation.[DesignationID] = Staff.[DesignationID] LEFT JOIN Groups ON Groups.[GroupID] = Staff.[GroupID] LEFT JOIN Section ON Section.[SectionID] = Staff.[SectionID] WHERE (Staff.[StaffName] IS NOT NULL)) AS test1 UNION ALL SELECT * FROM (SELECT Staff.[StaffID], Staff.[StaffName], Staff.[PhoneNo], Staff.[Photo], Staff.[EmpmType], Staff.[AcadStaff], Designation.[DesignationName], Section.[SectionName], Groups.[GroupName], Staff.[InternetAddr], ROW_NUMBER() OVER(ORDER BY Designation.[SortingOrder]) AS Rownum FROM Staff LEFT JOIN Designation ON Designation.[DesignationID] = Staff.[DesignationID] LEFT JOIN Groups ON Groups.[GroupID] = Staff.[GroupID] LEFT JOIN Section ON Section.[SectionID] = Staff.[SectionID] WHERE (Staff.[StaffName] IS NULL)) AS test2;"
                DeleteCommand="DELETE FROM Staff Where StaffID=@DSid" DataSourceMode="DataSet" CacheKeyDependency="MyCacheDependency">
                <DeleteParameters>
                    <asp:Parameter Name="DSid" Type="String" />
                </DeleteParameters>
            </asp:SqlDataSource>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" HeaderStyle-HorizontalAlign="Left" DataKeyNames="StaffID" CssClass="table table-striped table-condensed" ForeColor="#333333" GridLines="None" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AllowPaging="True" PageSize="8" OnPageIndexChanging="GridView1_PageIndexChanging">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:TemplateField ShowHeader="false">
                        <ItemTemplate>
                            <asp:Image ID="Image1" Height="50px" Width="40px" runat="server" ImageUrl='<%# Eval("Photo", "~/StaffPhoto/{0}") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="StaffID" HeaderText="Staff ID" ReadOnly="True" SortExpression="StaffID"/>
                    <asp:BoundField DataField="StaffName" HeaderText="Staff Name" SortExpression="StaffName"/>
                    <asp:BoundField DataField="PhoneNo" HeaderText="Ext. No" SortExpression="PhoneNo" />
                    <asp:BoundField DataField="DesignationName" HeaderText="Designation Name" SortExpression="DesignationName" />
                    <asp:BoundField DataField="InternetAddr" HeaderText="Email" SortExpression="InternetAddr" />
                    <%--            <asp:BoundField DataField="EmpmType" HeaderText="Employment Type" />
        <asp:BoundField DataField="AcadStaff" HeaderText="Staff Type" />--%>
                    <asp:CommandField ShowSelectButton="True" />
                    <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <asp:LinkButton ID="btndelete" runat="server" OnClick="btndelete_Click" Text="Delete" CommandName="Delete"
                                ForeColor="Black" />

                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField ShowHeader="False">
                        <ItemTemplate>
                            <asp:LinkButton runat="server" ID="btnUp" OnClick="Update_Click" ForeColor="Black">Update</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>

                </Columns>
                <EditRowStyle BackColor="#999999" />
                <HeaderStyle BackColor="white" Font-Bold="false" ForeColor="black" />
                <PagerStyle HorizontalAlign="Center" CssClass="pagination-ys" />
                <RowStyle BackColor="white" ForeColor="#333333" />
                <FooterStyle BackColor="white" ForeColor="black" />
                <SelectedRowStyle BackColor="#E2DED6" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                <EmptyDataTemplate>
                    <span style="color: red">* No Data Found.</span>
                </EmptyDataTemplate>
            </asp:GridView>
        </div>
        <div style="clear: both; height: 50px;">
        </div>
    </ContentTemplate>

</asp:UpdatePanel>

页面加载绑定的隐藏代码

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            GridView1.SelectedIndex = -1;
            GridView1.AllowPaging = false;
        }
        GridView1.DataBind();
        GridView1.AllowPaging = true;
    }

在 Select 行

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string subgpID = GridView1.SelectedRow.Cells[1].Text;
        BllStaff bs = new BllStaff();
        string sName = bs.GetStaffName(subgpID);
        if (sName == "")
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "alert", "StaffErrorMessage();", true);
        }
        else
        {
            Response.Redirect("StaffListDetails.aspx?staffid=" + subgpID);
        }
    }

StaffUpdate 页面 CS

public partial class StaffUpdate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Session["UT"] as string))
        {
            Response.Redirect("~/LoginPage.aspx");
        }
        lbMessage.Text = "";

        string ID = Request.QueryString["staffid"].ToString();

        lblSID.Text = ID;
        tbStaffID.Text = ID;
        if (Session["UT"].ToString() == "Admin")
        {
            ddlAT.Items.Remove("Admin");
        }
        if (ID == Session["StaffID"].ToString())
        {
            if (Session["UT"].ToString() == "Power Admin")
            {
                //Button1.Visible = true;
                OPassword.Attributes.Remove("style");
                NPassword.Attributes.Remove("style");
                NCPassword.Attributes.Remove("style");
            }
        }
        tbStaffID.ReadOnly = true;
        if (!Page.IsPostBack)
        {
            if (Session["UT"].ToString() != "Power Admin")
            {
                if (Session["UT"].ToString() != "Admin")
                {
                    ddlAT.Items.Insert(0, new ListItem("Staff", "Staff"));
                    ddlAT.Enabled = false;
                }
                else
                {
                    if (ID == Session["StaffID"].ToString()) { ddlAT.Items.Insert(0, new ListItem("Admin", "Admin")); }
                    else
                    {
                        ddlAT.Items.Insert(0, new ListItem("Staff", "Staff"));
                        ddlAT.Enabled = false;
                    }
                }
            }
            else
            {
                if (ID == Session["StaffID"].ToString())
                {
                    ddlAT.Items.Insert(0, new ListItem("Power Admin", "Power Admin"));
                    ddlAT.Enabled = false;
                }
                else
                {
                    BllAccount utAc = new BllAccount();
                    string utAccount = utAc.GetStaffUT(ID);
                    if (utAccount == "Admin")
                    {
                        ddlAT.Items.Insert(0, new ListItem("Admin", "Admin"));
                        ddlAT.Items.Insert(1, new ListItem("Staff", "Staff"));
                    }
                    else
                    {
                        ddlAT.Items.Insert(0, new ListItem("Staff", "Staff"));
                        ddlAT.Items.Insert(1, new ListItem("Admin", "Admin"));
                    }
                }
            }
        }




    }
    private string Encrypt(string clearText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        string SID = tbStaffID.Text;
        string oldP = Encrypt(tbPasswordOld.Text);
        string newP = tbPasswordNewC.Text;
        string ut = ddlAT.SelectedValue;
        string fileName = "";
        string OID = Request.QueryString["Staffid"].ToString();
        if (tbStaffID.Text != "")
        {
            if (this.ImageFileUpload.HasFile)
            {
                if (tbPasswordNewC.Text != "" || tbPasswordOld.Text != "")
                { //update id, password, photo and UT
                    //if (RegularExpressionValidator2.IsValid)
                    if (tbPasswordNewC.Text != "" && tbPasswordOld.Text != "")
                    {
                        string strsql = "select * FROM Account WHERE UserID='" + SID + "' and Password='" + oldP + "'";
                        DataTable dt = sql.ExecTable(strsql);
                        if (dt.Rows.Count > 0)
                        {
                            try
                            {
                                string[] validFileTypes = { "bmp", "gif", "png", "jpg", "jpeg" };
                                string ext = System.IO.Path.GetExtension(ImageFileUpload.PostedFile.FileName).ToLower();
                                bool isValidFile = false;
                                for (int i = 0; i < validFileTypes.Length; i++)
                                {
                                    if (ext == "." + validFileTypes[i])
                                    {
                                        isValidFile = true;
                                        break;
                                    }
                                }
                                if (!isValidFile)
                                {
                                    lbMessage.ForeColor = System.Drawing.Color.Red;
                                    lbMessage.Text = "* Invalid File. Please upload a File with extension " +
                                                   string.Join(", ", validFileTypes);
                                }
                                else
                                {
                                    FileInfo fi = new FileInfo(ImageFileUpload.FileName);
                                    string extion = fi.Extension;
                                    Session["fileEx"] = extion;
                                    fileName = "Ori" + SID + extion;
                                    //create instance for image class
                                    System.Drawing.Image myimg = default(System.Drawing.Image);
                                    //get uploaded image input stream
                                    using (myimg = System.Drawing.Image.FromStream(ImageFileUpload.PostedFile.InputStream))
                                    {
                                        //resize it using thumbnailimage method
                                        int width = myimg.Width;
                                        int height = myimg.Height;
                                        double bthumbWidth = 300 * width / height;
                                        int thumbWidth = Convert.ToInt32(bthumbWidth);
                                        myimg = myimg.GetThumbnailImage(thumbWidth, 300, null, IntPtr.Zero);
                                        MemoryStream str = new MemoryStream();
                                        //Save it in the server images folder
                                        myimg.Save(Server.MapPath("~\StaffPhoto\Ori\" + fileName), myimg.RawFormat);
                                        myimg.Dispose();
                                        //string strFilePath = Server.MapPath("~/StaffPhoto/") + "\" + fileName;
                                        //this.ImageFileUpload.SaveAs(strFilePath);
                                        imgUpload.ImageUrl = "~/StaffPhoto/Ori/" + fileName;
                                    }
                                    panCrop.Visible = true;
                                    string up = "a";
                                    Session["UpdateP"] = up;
                                }
                            }
                            catch (Exception ex)
                            {
                                lbMessage.ForeColor = System.Drawing.Color.Red;
                                lbMessage.Text = ex.Message + "* The Photo has failed to update. Please try again later!";
                            }
                        }
                        else
                        {
                            lbMessage.Text = "* Password Wrong!";
                        }
                    }
                    else
                    {
                        lbMessage.Text = "* Both password field must fill in!";
                    }
                }
                else //update photo, id and UT
                {
                    try
                    {
                        string[] validFileTypes = { "bmp", "gif", "png", "jpg", "jpeg", "ico", "jpe" };
                        string ext = System.IO.Path.GetExtension(ImageFileUpload.PostedFile.FileName).ToLower();
                        bool isValidFile = false;
                        for (int i = 0; i < validFileTypes.Length; i++)
                        {
                            if (ext == "." + validFileTypes[i])
                            {
                                isValidFile = true;
                                break;
                            }
                        }
                        if (!isValidFile)
                        {
                            lbMessage.ForeColor = System.Drawing.Color.Red;
                            lbMessage.Text = "* Invalid File. Please upload a File with extension " +
                                           string.Join(", ", validFileTypes);
                        }
                        else
                        {
                            FileInfo fi = new FileInfo(ImageFileUpload.FileName);
                            string extion = fi.Extension;
                            Session["fileEx"] = extion;
                            fileName = "Ori" + SID + extion;
                            //create instance for image class
                            System.Drawing.Image myimg = default(System.Drawing.Image);
                            //get uploaded image input stream
                            using (myimg = System.Drawing.Image.FromStream(ImageFileUpload.PostedFile.InputStream))
                            {
                                //resize it using thumbnailimage method
                                int width = myimg.Width;
                                int height = myimg.Height;
                                double bthumbWidth = 300 * width / height;
                                int thumbWidth = Convert.ToInt32(bthumbWidth);
                                myimg = myimg.GetThumbnailImage(thumbWidth, 300, null, IntPtr.Zero);
                                MemoryStream str = new MemoryStream();
                                //Save it in the server images folder
                                myimg.Save(Server.MapPath("~\StaffPhoto\Ori\" + fileName), myimg.RawFormat);
                                myimg.Dispose();
                                //string strFilePath = Server.MapPath("~/StaffPhoto/") + "\" + fileName;
                                //this.ImageFileUpload.SaveAs(strFilePath);
                                imgUpload.ImageUrl = "~/StaffPhoto/Ori/" + fileName;
                            }
                            panCrop.Visible = true;
                            string up = "b";
                            Session["UpdateP"] = up;
                        }
                    }
                    catch (Exception ex)
                    {
                        lbMessage.ForeColor = System.Drawing.Color.Red;
                        lbMessage.Text = ex.Message + "* The Photo has failed to update. Please try again later!";
                    }
                }
            }
            else //update password, id and UT
            {
                if (tbPasswordNewC.Text != "" || tbPasswordOld.Text != "")
                { //update id, password, photo and UT
                    //if (RegularExpressionValidator2.IsValid)
                    if (tbPasswordNewC.Text != "" && tbPasswordOld.Text != "")
                    {
                        string strsql = "select * FROM Account WHERE UserID='" + SID + "' and Password='" + oldP + "'";
                        DataTable dt = sql.ExecTable(strsql);
                        if (dt.Rows.Count > 0)
                        {
                            string upMessage = "You are trying to update the information for staff: " + SID;
                            string no = "3";
                            Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + fileName + "&NewPass=" + newP + "&UserT=" + ut);

                        }
                        else
                        {
                            lbMessage.Text = "* Password Wrong!";
                        }
                    }
                    else
                    {
                        lbMessage.Text = "* Both password field must fill in!";
                    }
                }
                else
                {
                    string upMessage = "You are trying to update the information for staff: " + SID;
                    string no = "4";
                    Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + fileName + "&NewPass=" + newP + "&UserT=" + ut);

                }
            }

        }
        else
        {
            lbMessage.Text = "* Staff ID must be provided";
        }
    }

    private void CheckName()
    {
        string SID = tbStaffID.Text;
        BllStaff bs = new BllStaff();
        string sName = bs.GetStaffName(SID);
        if (sName == "")
        {
            Response.Redirect("StaffListAdSearch.aspx");
        }
        else
        {
            Response.Redirect("StaffListDetails.aspx?staffid=" + SID);
        }
    }
    protected void btnUpNewP_Click(object sender, EventArgs e)
    {
        uploadNewP.Visible = true;
        uploadNewPD.Visible = false;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string staffid = tbStaffID.Text;
        string role = ddlAT.SelectedValue;
        Response.Redirect("AlertUSuc.aspx?staffid=" + staffid + "&role=" + role);
    }

    protected void btnCrop_Click(object sender, EventArgs e)
    {
        string SID = tbStaffID.Text;
        string oldP = Encrypt(tbPasswordOld.Text);
        string newP = tbPasswordNewC.Text;
        string ut = ddlAT.SelectedValue;
        string fileName = Path.GetFileName(imgUpload.ImageUrl);
        string filePath = Path.Combine(Server.MapPath("~/StaffPhoto/Ori"), fileName);
        string cropFileName = "";
        string cropFilePath = "";
        if (File.Exists(filePath))
        {
            System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath);
            System.Drawing.Rectangle CropArea = new System.Drawing.Rectangle(
                Convert.ToInt32(X.Value),
                Convert.ToInt32(Y.Value),
                Convert.ToInt32(W.Value),
                Convert.ToInt32(H.Value));
            try
            {
                Bitmap bitMap = new Bitmap(CropArea.Width, CropArea.Height);
                using (Graphics g = Graphics.FromImage(bitMap))
                {
                    g.DrawImage(orgImg, new System.Drawing.Rectangle(0, 0, bitMap.Width, bitMap.Height), CropArea, GraphicsUnit.Pixel);

                    cropFileName = SID + Session["fileEx"];
                    cropFilePath = Path.Combine(Server.MapPath("~/StaffPhoto"), cropFileName);
                    bitMap.Save(cropFilePath);
                    bitMap.Dispose();
                    string At = ddlAT.SelectedValue;
                    if (Session["UpdateP"].ToString() == "a")
                    {
                        string upMessage = "You are trying to update the information for staff: " + SID;
                        string no = "1";
                        Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + cropFileName + "&NewPass=" + newP + "&UserT=" + ut + "&DelFile=" + fileName, false);
                    }
                    else if (Session["UpdateP"].ToString() == "b")
                    {
                        string upMessage = "You are trying to update the information for staff: " + SID;
                        string no = "2";
                        Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + cropFileName + "&NewPass=" + newP + "&UserT=" + ut + "&DelFile=" + fileName, false);
                    }
                    g.Dispose();
                }
            }
            catch (Exception ex)
            {
                lbMessage.Text = ex.Message;
            }
            finally {
                orgImg.Dispose();
            }
        }

    }
}

示例背后的 AlertUpdate 代码

string strsql = "select UserType FROM Account WHERE UserID='" + OID + "'";
                DataTable dt = sql.ExecTable(strsql);
                if (dt.Rows.Count > 0)
                {
                    uStaffA.UpdateAccountbaseOnStaffID(OID, OID, ut);
                }

更新工作人员帐户基础

public int UpdateAccountbaseOnStaffID(string staffid, string NStaffId, string ut)
    {
        StringBuilder sql;
        SqlCommand sqlCmd;
        int result = 0;
        //int newOrderId = 0;
        // create order header
        SqlConnection conn = dbConn.GetConnection();
        sql = new StringBuilder();
        sql.AppendLine("UPDATE Account");
        sql.AppendLine("SET UserID=@Nid, StaffID=@Nid, UserType=@UserType where StaffID=@Oid");

        try
        {
            conn.Open();

            sqlCmd = new SqlCommand(sql.ToString(), conn);

            sqlCmd.Parameters.AddWithValue("@Oid", staffid);
            sqlCmd.Parameters.AddWithValue("@Nid", NStaffId);
            sqlCmd.Parameters.AddWithValue("@UserType", ut);

            result = sqlCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            errMsg = ex.Message;
        }
        finally
        {
            conn.Close();
        }

        return result;

    }

AlertUpdateSuc

public partial class AlertUpdateSuc : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Request.QueryString["MesNo"].ToString() == "1")
        {
            Session.Clear();
            Response.Redirect("LoginPage.aspx");
        }
        else if (Request.QueryString["MesNo"].ToString() == "2")
        {
            Response.Redirect("StaffListAdSearch.aspx");
        }

    }
}

简而言之,即使照片正确更新,在我刷新页面之前,旧照片仍然显示。

任何想法都会有所帮助!谢谢!

如果你更新图像,并不意味着你的gridview也必须更新。什么都不会自己执行。您必须执行命令。更新图像后,您必须重新绑定 gridview。

事实证明,为了正确地重新绑定您的照片,您需要做的是更新图像 URL。

但是,因为我们的图像 URL 永远不会改变,我必须做的是将一些数据添加到 URL 中,以便它变得唯一并正确更新。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Image img = e.Row.FindControl("Image1") as Image;
            string url = img.ImageUrl;
            string modified = url + "?time=" + DateTime.Now.ToString();
            img.ImageUrl = modified;
        }
    }

通过执行上述操作,GridView 中的图像将被更新。 这也适用于 DetailsView,只需这样做:

protected void ViewEmployeeDetails_DataBound(object sender, EventArgs e)
    {
        Image img = ViewEmployeeDetails.FindControl("Image1") as Image;
        string url = img.ImageUrl;
        string modified = url + "?time=" + DateTime.Now.ToString();
        img.ImageUrl = modified;
    }