我使用ListView
控件和EntityDataSource
将图像插入我的数据库。在MemberImage列的InsertItemTemplate
Image
和FileUpload
控件中。插入数据后,image列在数据库中显示为null。
任何正确程序的方法都将受到赞赏。
我的代码段如下所示:
<asp:ListView ID="IndividualListView" runat="server" DataKeyNames="IndividualId" DataSourceID="IndividualDataSource" InsertItemPosition="LastItem"
oniteminserting="IndividualListView_ItemInserting"
onselectedindexchanged="IndividualListView_SelectedIndexChanged">
<InsertItemTemplate>
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
Text="Insert" BorderStyle="Ridge" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" BorderStyle="Ridge" />
</td>
<td>
<asp:TextBox ID="IndividualIdTextBox" runat="server"
Text='<%# Bind("IndividualId") %>' />
</td>
<td>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Bind("MemberImage") %>'/><br />
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</td>
</InsertItemTemplate>
</asp:ListView>
<asp:EntityDataSource ID="IndividualDataSource" runat="server"
ConnectionString="name=SheepGateEntities"
DefaultContainerName="SheepGateEntities" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" EntitySetName="Individuals"
EntityTypeFilter="Individual" Include="Counsellings, Households, Services">
</asp:EntityDataSource>
代码隐藏页面如下:
protected void IndividualListView_ItemInserting(object sender, ListViewInsertEventArgs e)
{
FUpload = (FileUpload)IndividualListView.InsertItem.FindControl("FileUpload1");
FLabel = (Label)IndividualListView.InsertItem.FindControl("Label1");
try
{
FileUpload img = (FileUpload)FUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = FUpload.PostedFile;
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
e.Values.Add("MemberImage", FUpload.FileName);
}
catch
{
FLabel.BackColor.Equals("Red");
FLabel.Text = "There was an error";
}
}