I have a page that uses a gridview which has a datasourceID declared, the files display correctly. However, whenever i update a photo of the gridview, the gridview does not update correctly, despite the photo in my folders where the gridview retrieves from being updated already. The only way i can get them to retrieve the right photos are if i actually press F5 or reload the project. The gridview is also inside a updatepanel.
<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>
code behind for pageload binding
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.SelectedIndex = -1;
GridView1.AllowPaging = false;
}
GridView1.DataBind();
GridView1.AllowPaging = true;
}
On Select for row
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 Code Behind sample
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");
}
}
}
In short even though the photo updates correctly, the old photo is still being displayed until i refresh the page.
Any ideas will be helpful! thank you!
Turns out, In order to rebind your photo correctly, what you have to do is to update the Image URL.
However, because our Image URL never changes, what i had to do was add in some data into the URL so that it becomes unique and updates correctly.
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;
}
}
By doing what i did above, the Image in the GridView will be updated. This works for DetailsView as well, by simply doing it this way:
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;
}