Deleting images from folder by gridview - c#

I have a grid view which I populated with images from a folder. I am trying to delete the image by getting their path name but it always returns me null:
Here are my codes to populate the grid view with images:
protected void GetImage()
{
string path = HttpContext.Current.Request.PhysicalApplicationPath + #"Story/Food Fit For A King";
string[] files = System.IO.Directory.GetFiles(path, "*.jpg");
IList<ImageFileInfo> imageFileList = new List<ImageFileInfo>();
foreach (string strFileName in files)
{
// Change the Absolute path to relative path of File Name and add to the List
imageFileList.Add(new ImageFileInfo { FileName = ResolveUrl(strFileName.Replace(Server.MapPath("/"), "~/")) });
}
gvStory.DataSource = imageFileList;
gvStory.DataBind();
}
And below is my code to delete :
protected void gvStory_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView gvQuestion = (GridView)sender;
int row = e.RowIndex;
// Extract Values.
// string imageName = (TextBox)gvStory.Rows[row].Cells[0].FindControl("TextBox1");// RETURNS NULL
Image img = (Image)gvStory.Rows[row].Cells[0].FindControl("Image1");
string url = img.ImageUrl;
// string fileName = Path.GetFullPath(url); // RETURNS NULL
//string fileName = Path.Combine(Server.MapPath(#"Story/Food Fit For A King"), imageName);
File.Delete(fileName);
GetImage();
}
Am I doing the correct way to the the filepath of the image? But I need the full path of the image to delete it, I tried to use Path.GetFullPath(url) , it doesn't work. Need help on this.
And heres the aspx html side:
<asp:TemplateField HeaderText="Images">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("FileName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("FileName") %>' Width="240" Height="160" />
</ItemTemplate>
</asp:TemplateField>
Need help on this.

If gridview row will be in edit mode, then only you can find the control that are inside <EditItemTemplate> tag. in editmode, you will get rowindex as -1. in other mode, rowindex will be greater than -1, then you can find controls that are inside <ItemTemplate> tag. Otherwise you will get null values. So, you can try this way,
protected void gvStory_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView gvQuestion = (GridView)sender;
int row = e.RowIndex;
string fileName ="";
if(row==-1)
{
string imageName = (TextBox)gvStory.Rows[row].Cells[0].FindControl("TextBox1");
fileName = Path.Combine(Server.MapPath(#"Story/Food Fit For A King"),imageName);
}
else
{
Image img = (Image)gvStory.Rows[row].Cells[0].FindControl("Image1");
string url = img.ImageUrl;
fileName = Path.GetFullPath(url);
}
File.Delete(fileName);
GetImage();
}

Related

Asp.net C#: Cannot get inner content of fileuploads because the contents are not literal

I'm developing a web application using asp.net c#. I'm trying to create fileuploads dynamically. using the following code:
FileUpload[] fileuploadsarr = new FileUpload[uploads_table.Rows.Count];
int c = 0;
foreach (DataRow row in uploads_table.Rows)
{
Label att_name = new Label();
att_name.Text = row["TYPE"].ToString();
FileUpload fileupload = new FileUpload();
fileupload.CssClass = "form-control";
fileupload.ID = "fileupload"+ row["ID"].ToString();
fileupload.Attributes.Add("runat", "server");
fileuploads.Controls.Add(att_name);
fileuploads.Controls.Add(fileupload);
fileuploadsarr[c] = fileupload;
c = c + 1;
}
Session["myfileuploadsarr"] = fileuploadsarr;
when i try to reference the postedfile for each fileupload i got the null pointer exception. When i have debugged the code I've found this exception inside the parent attribute of the file upload
Parent = {InnerText = {System.Web.HttpException (0x80004005): Cannot get inner content of fileuploads because the contents are not literal.
Note: I'm adding the fileuploads on a div
<div id="fileuploads" runat="server">
</div>
i reference filesupload through:
FileUpload[] temp = (FileUpload[])Session["myfileuploadsarr"];
foreach (FileUpload row in temp)
{
OracleCommand cmd_docs = new OracleCommand();
System.IO.Stream fs = row.PostedFile.InputStream;
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
...
}
I think you better could use a ListView. It saves you the trouble of generating dynamic controls. Note the use of DataKeyNames
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("TYPE") %>'></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="form-control" />
<br />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" Text="Upload files" OnClick="Button1_Click" />
And then in code behind you bind data to the ListView and process the uploaded files on a button click.
protected void Button1_Click(object sender, EventArgs e)
{
//loop all items in the listview
for (int i = 0; i < ListView1.Items.Count; i++)
{
//get the id from the datakeys if needed
int ID = Convert.ToInt32(ListView1.DataKeys[i].Values[0]);
//use findcontrol to locate the fileupload and cast it back
FileUpload fu = ListView1.Items[i].FindControl("FileUpload1") as FileUpload;
//check if it exists and has a file
if (fu != null && fu.HasFile)
{
//save the file
}
}
}
The binding of the DataTable uploads_table to the ListView to make this demo complete.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//bind the datatable to the listview
ListView1.DataSource = uploads_table;
ListView1.DataBind();
}
}

Object is set to Null Reference when editing gridview

In my web application, I have a grid-view and this grid-view is databounded. Above this grid-view, I have a text box where user can first enter the Employee ID and show the Employee Name in the grid view. In the grid view, it has the edit icon. When the user hit that edit icon, some text boxes in the grid view will appear and the use can edit the text in the text box. I got it working so far. However, my problem is when I am trying to edit the empty text box in the grid view, it gave me this error:
Object is not set to an instance of an object
All I did is to check if the text box is null. This does ignore the error but not really what I want
protected void txtEditedEmployeeID_TextChanged(object sender, EventArgs e)
{
DatabaseManager dbManager = Common.GetDbManager();
foreach (GridViewRow row in gridViewAddEmployee.Rows)
{
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
if (txtEmployee!= null)
{
string personID = txtEmployee.Text;
DataSet dsRE = dbManager.GetEmployeeNameByID(personID);
for (int i = 0; i < dsRE.Tables[0].Rows.Count; i++)
{
string employeeFirstName = dsRE.Tables[0].Rows[i]["FIRST_NAME"].ToString();
string employeeLastName = dsRE.Tables[0].Rows[i]["LAST_NAME"].ToString();
((TextBox)row.FindControl("txtEmployeeName")).Text = staffLastName + " " + staffFirstName;
}
}
else
{
}
}
}
HTML ASP.NET Code
<asp:TemplateField HeaderText="EmployeeID">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeID" runat="server" AutoPostBack="true" OnTextChanged= "txtEditedEmployeeID_TextChanged" Text='<%#Bind("Employee_ID") %>'Width="90px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeID" runat="server" CssClass="GridInput" Text='<%#Bind("Employee_ID") %>'Width="90px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" runat="server" ReadOnly ="true" Text='<%#Bind("Full_Name") %>'Width="90px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeName" runat="server" CssClass="GridInput" Text='<%#Bind("Full_Name") %>'Width="90px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
As on Edit txtEmployeeID will appear for that row only Not for all the rows of GridView and on TextBox Change event you are finding all row edited TextBox which is not appear till now so you may try this:
protected void txtEditedEmployeeID_TextChanged(object sender, EventArgs e)
{
DatabaseManager dbManager = Common.GetDbManager();
TextBox txt = sender as TextBox; // Edited TextBox
GridViewRow row = (txt.NamingContainer as GridViewRow);// Row of Edited TextBox
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
string personID = txtEmployee.Text;
DataSet dsRE = dbManager.GetEmployeeNameByID(personID);
for (int i = 0; i < dsRE.Tables[0].Rows.Count; i++)
{
string employeeFirstName = dsRE.Tables[0].Rows[i]["FIRST_NAME"].ToString();
string employeeLastName = dsRE.Tables[0].Rows[i]["LAST_NAME"].ToString();
((TextBox)row.FindControl("txtEmployeeName")).Text = staffLastName + " " + staffFirstName;
}
}
Try this:
Instead of
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
if (txtEmployee!= null)
{
string personID = txtEmployee.Text;
You should write it like this
TextBox txtEmployee = new TextBox();
txtEmployee = (TextBox)row.FindControl("txtEmployeeID");
if (!string.isNullorEmpty(txtEmployee.Text))
{
string personID = txtEmployee.Text;

How to upload image file in gridview?

I have a gridview that shows an image as part of a column. In Edit mode, I would like to let the user upload a new image file, so I'm using the FileUpload control in the edit part of the template.
When I click on update it's showing me this:
My code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lb = GridView1.HeaderRow.FindControl("Label1") as Label;
GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("fileupload") as FileUpload;
if (fu.HasFile)
{
string file = System.IO.Path.Combine(Server.MapPath("~/uploadedimages/"), fu.FileName);
fu.SaveAs(file);
using (Ex_RepeaterEntities entities = new Ex_RepeaterEntities())
{
Student students = (from e1 in entities.Students
where e1.Id == Convert.ToInt32(lb.Text)
select e1).First();
students.Images = file;
entities.SaveChanges();
}
}
}
After a lot of searching I found solution of above error by using this code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int RowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("fileupload") as FileUpload;
if (fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/uploadedimages/" + fileUpload.FileName));
}
}
and at page.aspx:
<asp:TemplateField HeaderText="Upload Image" SortExpression="Names">
<EditItemTemplate>
<asp:FileUpload runat="server" ID="fileupload" />
</EditItemTemplate>
<ItemTemplate>
<asp:Image ImageUrl="~/uploadedimages/1.jpg" runat="server" ID="image" />
</ItemTemplate>
</asp:TemplateField>
But a little problem here is to solve which is that file is not saving.
Finally got my own solution of above post. Here is code to be changed:
if (fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("uploadedimages/" + fileUpload.FileName));
}

Setting ImageSrc for each template

So I am in a confusing situation right now, I have a ListView with an ItemTemplate that contains an Image element:
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<asp:Image ID="Image1" class="main" runat="server" ImageUrl='<%# Eval("photo1") %>' />
</ItemTemplate>
</asp:ListView>
In my click event I have the following code:
protected void btn_search_Click(object sender, EventArgs e)
{
var img = ListView1.Items[0].FindControl("Image1") as Image;
var lbl = ListView1.Items[0].FindControl("lbl_ID") as Label;
string image = img.ImageUrl;
foreach (ListViewItem item in ListView1.Items)
{
if (img.ImageUrl == "defaultcar.jpg")
{
img.ImageUrl = "images/defaultcar.jpg";
}
else
{
img.ImageUrl = "images/" + "44/" + image;
}
}
}
So in my DB I have 2 images, one called "defaultcar.jpg" and another called "car.jpg" what I am trying to do is create the correct path for each image, I have debugged everything and it seems the first ItemTemplate is displaying "images/44/defaultcar.jpg" and the second ItemTemplate is displaying "car.jpg", it should be the other way round, "images/44/car.jpg" and "images/defaultcar.jpg"
does anyone know what I am doing wrong?
If I understand your issue, you can solve it as below:
First create method to return Image url like:
protected string GetImageUrl(object imageUrl)
{
if(imageUrl == null)
return "";
if(imageUrl.ToString() == "defaultcar.jpg")
return = "images/defaultcar.jpg";
else
return "images/44/" + imageUrl.ToString();
}
Then update .aspx file:
<asp:Image ID="Image1" class="main" runat="server" ImageUrl='<%# GetImageUrl(Eval("photo1")) %>' />

adding functionality to an imageButton in a gridview

Hallo there
I have an ImageButton control as part of a GridView control that is displayed as an ItemTemplate and in the same GridView I have a regular Button control to which I added some code like this.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "addToSession")
{
//get the row index stored in the CommandArgument property
int index = Convert.ToInt32(e.CommandArgument);
//get the gridview row where the command is raised
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//values stored in the text property of the cells
string ISBN = selectedRow.Cells[0].Text;
string bookTitle = selectedRow.Cells[1].Text;
string image = selectedRow.Cells[2].Text;
Service s = new Service();
Session["ISBN"] = ISBN;
Session["bookTitle"] = bookTitle;
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
if (Session["userName"] == null)
{
Response.Redirect("registerPage.aspx");
}
else
{
Response.Redirect("RateBook.aspx");
}
}
else if (e.CommandName == "ratedBooks")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string bookTitle = selectedRow.Cells[1].Text;
Service s = new Service();
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
Response.Redirect("BookRated.aspx");
}
when I run this code I get a format exception and again I am not sure why.
I have altered the image button a bit and nested the image in a link button which seems to be more correct.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="ratedBooks">
<asp:Image ID="ImageButton1" ImageUrl='<%#Eval("pictureUrl") %>'
runat="server" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Advice perhaps as to what to do
regards
ImageButton.CommandName is a valid property and it should work the same as Button.CommandName.
The problem, then, is most likely in your GridView1_RowCommand procedure. Can you post the entire procedure code including the part intended to handle the ImageButton click?

Categories

Resources