ASP。 NET Gridview与DataSourceID无法正确绑定

时间:2016-01-31 08:07:05

标签: c# asp.net gridview updatepanel

我有一个使用gridview的页面,其中声明了datasourceID,文件正确显示。但是,每当我更新gridview的照片时,gridview都无法正确更新,尽管我的文件夹中的照片已经从gridview检索到已经更新。我可以让他们检索正确的照片的唯一方法是,如果我实际上按F5或重新加载项目。 gridview也在更新面板内。

<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;
    }

选择行

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 Page 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);
                }

Updateaccountbaseonstaffid

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");
        }

    }
}

简而言之,即使照片更新正确,旧照片仍会显示,直到我刷新页面。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

原来,为了正确重新绑定你的照片,你要做的就是更新图片网址。

但是,由于我们的图片网址永远不会更改,我所要做的就是在网址中添加一些数据,以便它变得唯一并正确更新。

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中的Image将会更新。 这也适用于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;
    }