【发布时间】:2023-03-27 02:25:02
【问题描述】:
这就是我得到一个名为 gridview1 的 datagridviewer 和一个 fileupload1 的交易,当我上传一个文件时,它会使用文件名和路径更新数据库中的 gridview1 和表,并将所述文件存储在文件夹“Mag”中......但是现在我想做的是相反我得到了如何使用gridview删除表条目但是从文件夹“Mag”中删除文件不起作用在C#或代码隐藏中使用了以下代码
protected void GridView1_Del(object sender, EventArgs e)
{
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
string[] Files = Directory.GetFiles(@"i:/Website/WebSite3/Mag/");
foreach (string file in Files)
{
if (file.ToUpper().Contains(DeleteThis.ToUpper()))
{
File.Delete(file);
}
}
}
它给了我错误
“对象引用未设置为对象的实例。”
请告诉我我做错了什么是新的,并且不必深入了解平台,因此我们将不胜感激任何和所有帮助 提前致谢 标记
这是我找到的答案感谢 Tammy 和其他所有人的所有答案
好的,这里的交易目标函数从gridview和数据库表中删除文件详细信息,并从存储文件的项目文件夹中删除文件
在您想要包含的 gridview 的脚本部分中
OnRowDeleting="FuntionName"
没有
OnSelectedIndexChanged = "FuntionName"
或
OnRowDeleted="FuntionName"
然后在 C# 代码中(代码隐藏)
protected void FuntionName(object sender, GridViewDeleteEventArgs e)
{
// storing value from cell
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
// full path required
string fileName = ("i:/Website/WebSite3/Mag/" + cell.Text);
if(fileName != null || fileName != string.Empty)
{
if((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
}
}
仅供想学习的人参考
OnRowDeleting="FuntionName" 用于在删除一行之前,您可以像我一样取消删除或对数据运行函数
OnRowDeleted="FuntionName" 它直接删除
【问题讨论】:
-
在什么情况下您会遇到异常?
-
在哪一行给出异常?
GridView1.SelectedRow.Cells[0].Text在我看来很可疑 -
从您的代码字符串中删除这一行 DeleteThis = GridView1.SelectedRow.Cells[0].Text;返回正确的文件路径?
-
试试这个:if ((System.IO.File.Exists(fileName))) System.IO.File.Delete(fileName);
-
非常感谢@گلی 你的代码工作正常。