views:

39

answers:

3

I have a Gridview which displays the filenames in the database.

alt text

I have written code for deleting filename entry from database, but I also want to delete it from the directory, so how do I retrieve filename from Gridview ?

I don't want to execute another select command for retrieving filename.

Code :

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
     int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
     sdsFiles.DeleteCommand = "Delete from Files where Fid = @id";
     sdsFiles.DeleteParameters.Clear();
     sdsFiles.DeleteParameters.Add("id",Fid.ToString());
     sdsFiles.Delete();
     System.IO.Directory.Delete(Server.MapPath("~/Data/"));
}

Thanks.

+2  A: 

Use the following code and do steps;

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
    sdsFiles.DeleteCommand = "Delete from Files where Fid = @id";
    sdsFiles.DeleteParameters.Clear();
    sdsFiles.DeleteParameters.Add("id",Fid.ToString());
    sdsFiles.Delete();
    string fileName = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text;
    System.IO.File.Delete(Server.MapPath("") + "\\" + fileName);
}
  1. you must go to gridview columns window
  2. Convert to file name column to TemplateField
  3. Save and Exit GridView Columns window
  4. Go to Files column template design
  5. Set label id "Label1"
  6. Go to code and use it

    alt text

ismailperim
+1 Thanks for the Illustration :)
Searock
+1 for the pics :)
Ninja Dude
+2  A: 

For performance reasons I, wouldn't go overboard adding lots of keys with this, but you can set the GridView's DataKeys property to include the filename column as well as the fid that you already set by setting the GridViews DataKeyNames property equal to "FID,Filename", then retrieve the DataKey by row during your delete method using the GridView1.DataKeys[e.RowIndex].Values method instead, where retrieve the DataKey by index, so if your DataKeys are "FID,filename" FID would be GridView1.DataKeys[e.RowIndex].Values[0] and filename would be GridView1.DataKeys[e.RowIndex].Values[1].

ben f.
+1 Thanks for your advice : )
Searock
+2  A: 

I get the string (file name) direct this way:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
     GridView1.SelectedIndex = e.RowIndex;         
     string fileName = GridView1.SelectedRow.Cells[1].Text;
     System.IO.File.Delete(Server.MapPath("") + "\\" + fileName);    

     int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
     sdsFiles.DeleteCommand = "Delete from Files where Fid = @id";
     sdsFiles.DeleteParameters.Clear();
     sdsFiles.DeleteParameters.Add("id",Fid.ToString());
     sdsFiles.Delete();

     GridView1.SelectedIndex = -1;
}

Maybe there is ever faster, I am not sure.

Aristos
+1 please replace sdsFiles by GridView1 : )
Searock
@Searock Ok thank (mistake) :)
Aristos