开发者

Retrieving filename column form Gridview

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

Retrieving filename column form Gridview

I have written code for deleting filename en开发者_Go百科try 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.


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

    Retrieving filename column form Gridview


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].


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜