[英]Trying to use File Upload in Listview? Update not working
这是我的列表视图。 我正在使用OnItemCommand来引用代码隐藏中的代码。 在这里,我尝试使用新的FileUpload控件更新数据库。
<%--Listview--%>
<asp:ListView runat="server" ID="livLocation" class="container"
DataKeyNames="LocationID"
DataSourceID="sdsListViewLocation"
EmptyDataText="No data to display"
InsertItemPosition="FirstItem"
OnItemInserted="livLocation_ItemInserted"
OnItemUpdated="livLocation_ItemUpdated"
OnItemDeleted="livLocation_ItemDeleted"
OnItemCanceling="livLocation_ItemCanceling"
OnItemCommand="livLocation_ItemCommand">
</asp:ListView>
插入工作得很好。 执行更新时,所有FindControl都会抛出 Null 错误。 我相信出于某种原因FindControls不适用于Update 。 我曾尝试为每个控件分配自己的 ID,但这仍然没有解决问题。 我一直在参考这篇文章,但到目前为止没有任何帮助: 在 Listview asp.net 中使用 fileupload 上传图像
protected void livLocation_ItemCommand(object sender, ListViewCommandEventArgs e)
{
//
if (e.CommandName == "Insert")
{
// Find controls on insert.
TextBox txtLocation = (TextBox)livLocation.InsertItem.FindControl("txtLocation");
TextBox txtImage = (TextBox)livLocation.InsertItem.FindControl("txtImage");
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
// Get today's date
String strDate = DateTime.Now.ToString("MM-dd-yyyy-h-m-stt");
// If file is there to upload.
if (fuiImage.HasFile)
{
// Set path.
String strFileName = txtLocation.Text + "-" + strDate + ".jpg";
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + strFileName;
// Save file.
fuiImage.SaveAs(strPath);
// Fill Image textbox
txtImage.Text = strFileName;
}
else
{
// Do nothing
}
}
else if (e.CommandName == "Update")
{
// Find controls on insert.
TextBox txtLocation = (TextBox)livLocation.InsertItem.FindControl("txtLocation");
TextBox txtImage = (TextBox)livLocation.InsertItem.FindControl("txtImage");
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
// Get today's date
String strDate = DateTime.Now.ToString("MM-dd-yyyy-h-m-stt");
// If file is there to upload.
if (fuiImage.HasFile)
{
// Set path.
String strFileName = txtLocation.Text + "-" + strDate + ".jpg";
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + strFileName;
// Save file.
fuiImage.SaveAs(strPath);
// Fill Image textbox
txtImage.Text = strFileName;
}
else
{
// Do nothing
}
}
else if (e.CommandName == "Delete")
{
// Delete file.
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + fuiImage.FileName;
System.IO.File.Delete("strPath");
}
else
{
// Do nothing
}
}
}
正如所讨论的那样,使用发送者对象来获得更好的可维护性总是很好的。 对于您的问题,请访问以下链接以获取已编辑的项目,因为您的语法不正确: https : //docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.listview.itemediting?视图=网络框架-4.8
它显示了有关项目编辑的更多详细信息以及如何使用新的编辑索引获取已编辑的项目。
这
(TextBox)livLocation.InsertItem
不正确,它必须是EditItem
所以它将是(FileUpload)(sender as ListView).EditItem.FindControl.....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.