Retrieving filename column form Gridview
I have a Gridview which displays the filenames in the database.
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);
}
you must go to gridview columns window
Convert to file name column to TemplateField
Save and Exit GridView Columns window
Go to Files column template design
Set label id "Label1"
Go to code and use it
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.
精彩评论