正在尝试在Listview中使用文件上载?更新不起作用



这是我的ListView。我正在使用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>

插入效果非常好。执行Update时,会为所有FindControls引发Null错误。我认为由于某种原因,FindControls不适用于更新。我试过让每个控件都有自己的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
}
}
}

正如所讨论的,使用sender对象以提高以后的可维护性总是很好的。对于您的问题,请访问以下链接以获取编辑的项目,因为您的语法不正确:https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.listview.itemediting?view=netframework-4.8

它显示了有关项目编辑的更多详细信息,以及如何使用新的编辑索引获取编辑后的项目。


(TextBox)livLocation.InsertItem不正确,必须是EditItem所以它将是(FileUpload)(sender as ListView).EditItem.FindControl.....

最新更新