Greeting all
I viewed these article by Upendra Pratap Shahi to make (CRUD) on Image by Gridview
https://www.c-sharpcorner.com/UploadFile/77a82c/binding-image-with-gridview-and-update-image-in-gridview/
Actually I use a piece from last article to make delete photo from folder (Not delele a row completly) see fig.1
A methode to delete photo from folder by Upendra Pratap Shahi :
- protected void ImgDelFrmfolder(string imagename)
- {
-
- string file_name = imagename;
- string path = Server.MapPath(@"~/images/products/" + imagename);
- FileInfo file = new FileInfo(path);
- if (file.Exists)
- {
- file.Delete();
- LBgvSu.Text = file_name + " file deleted successfully";
- }
- else
- {
- LBgvFi.Text = file_name + " This file does not exists ";
-
- }
-
- }
I add Button under Image to Delete Image:
- <ItemTemplate>
- <div style="text-align:center">
- <asp:Image ID="IMG_GVProduct" runat="server" Height="80px" ImageUrl='<%# Eval("P_photo") %>' Width="80px" /><br />
- <asp:Button ID="DelImg" runat="server" Height="25" Text="Delete Photo" CssClass="btn btn-outline-danger" Font-Size="Small" Font-Overline="False" CommandName="Del_photo" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'/>
- </div>
- </ItemTemplate>
What I add extara Idea and extara code?
My Idea is to Update a two colums in table (photo_path and Photo_name) with (Null) value when an admin delete image.
My update code, is calling command name ("Del_photo") for Delete button, by ("GridView1_RowCommand"), see code below:
- protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
- {
-
- if (e.CommandName == "Del_photo")
- {
-
-
- int rowInx = Convert.ToInt32(e.CommandArgument);
-
-
- GridViewRow row = GridView1.Rows[rowInx];
-
-
- string Lb_name = (row.FindControl("Lb_ImgName") as Label).Text;
-
-
- ImgDelFrmfolder(Lb_name);
-
- using (SqlConnection sqlcon = new SqlConnection(connectionString))
- try
- {
- sqlcon.Open();
- string query = "UPDATE Products SET P_photo = @P_photo, Pho_Name=@Pho_Name WHERE (Id = @Id)";
- SqlCommand sqlcmd2 = new SqlCommand(query, sqlcon);
- sqlcmd2.Parameters.AddWithValue("@P_photo", "");
- sqlcmd2.Parameters.AddWithValue("@Pho_Name", "");
- sqlcmd2.Parameters.AddWithValue("@Id", Convert.ToInt32(rowInx.ToString()));
- sqlcmd2.ExecuteNonQuery();
- GridView1.EditIndex = -1;
- sqlcon.Close();
- GridView1.DataBind();
- }
- catch (Exception ex)
- {
- LBgvFi.Text = ex.Message;
- }
- }
-
- }
What happen?
a code run correctly, no bugs no errors, and an image delete from folder complety.
See fig.2 below:
But if I back to table and check a new changes for two columns nothing happen(to clear old values and keep it null).
I don't know what a true method if I have wrong way, or my coding need to rebuilding;
I'm trying and still until this moment to fix that.
Thnks for any help