我有关于文章出版物的申请。我正在尝试使表单插入一篇文章。我想创建一个文件上传部分。我正在使用datalist并希望上传文章。问题在于代码背后,它向我显示了这个错误:
System.NullReferenceException:未将对象引用设置为实例 一个对象。
<asp:DataList ID="datalist2" runat="server"
onitemcommand="datalist2_ItemCommand">
<ItemTemplate>
<section id="main" class="column" runat="server" style="width:900px;">
<article class="module width_full" style="width:900px;">
<header><h3>Post New Article</h3></header>
<div class="module_content">
<asp:Label ID="Label1" runat="server">Tema</asp:Label>
<fieldset>
<asp:TextBox ID="txtTema" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="Label6" runat="server">Abstrakti</asp:Label>
<fieldset>
<asp:TextBox ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>
</fieldset>
<asp:Label ID="Label4" runat="server">Keywords</asp:Label>
<fieldset>
<asp:TextBox ID="txtKeywords" runat="server"></asp:TextBox>
<asp:FileUpload ID="FileUploadArtikull" runat="server" Height="43px"
style="margin-left: 0px" />
</fieldset>
<asp:Label ID="Label5" runat="server">Kategoria</asp:Label>
<fieldset>
<asp:TextBox ID="txtKategoria" runat="server"></asp:TextBox>
</fieldset>
<asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
</div>
</article>
</section>
</ItemTemplate>
</asp:DataList>
FileUpload FileUploadArtikull = (FileUpload)datalist2.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Max 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("@filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('ERROR');", true);
}
答案 0 :(得分:0)
您不能直接从datalist2访问任何控件,您必须遍历每个datalist项。
foreach (DataListItem item in datalist2.Items)
{
FileUpload FileUploadArtikull = (FileUpload)item.FindControl("FileUploadArtikull");
if (FileUploadArtikull.HasFile)
{
int filesize = FileUploadArtikull.PostedFile.ContentLength;
if (filesize > 4194304)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Max 4MB');", true);
}
else
{
string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
//add parameters
command.Parameters.AddWithValue("@filename", filename);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Bind();
FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
Response.Redirect("dashboard.aspx");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('ERROR');", true);
}
}