You need to to have a
FileUpload
control within
EditItemTemplat
e so you can browse new image.You can then update the image from your database just like updating normal data in your database. The idea is to get the existing
ID
of the row that holds your image and then update it with the new image (either update the path or the image itself ~ that depends on how you store the images).
For example your
GridView
would have something like this:
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image runat="server" ID="Image1" />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
Since you were storing the image as
Binary
file to display them, then you don't have to access the
Image
itself to update it. Instead, you just need to update the data from database and rebind your
GridView
to reflect the changes. Here's an example that I wrote many years ago:
FAQ: Displaying Image from Database to GridView Control[
^]
Here's a quick example:
private void Update(int ID, string name, decimal price, string description,byte[] image){
using (SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE")) {
string sql = "UPDATE YourTableName SET Name = @Name, Price = @Price, Description = @Description, Image = @Image WHERE ID = @ID";
using (SqlCommand cmd = new SqlCommand(sql, connection)) {
cmd.Parameters.AddWithValue("@ID", ID);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@Description", description);
cmd.Parameters.AddWithValue("@Image", image);
cmd.ExecuteNonQuery();
}
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GridView1.Rows[e.RowIndex].Cells[0].Text;
string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string price = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
FileUpload fileUpload = (FileUpload)GridView1.Rows[e.RowIndex].Cells[3].FindControl("FileUpload1");
string description = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
byte[] theImage = new byte[fileUpload.PostedFile.ContentLength];
HttpPostedFile Image = fileUpload.PostedFile;
Image.InputStream.Read(theImage, 0, (int)fileUpload.PostedFile.ContentLength);
int length = theImage.Length;
string fileName = fileUpload.FileName.ToString();
string type = fileUpload.PostedFile.ContentType;
int size = fileUpload.PostedFile.ContentLength;
if (fileUpload.PostedFile != null && fileUpload.PostedFile.FileName != "")
{
Update(id,name,price,description,theImage);
}
GridView1.EditIndex = -1;
BindGridView();
}