我目前有一个表单,其中有一个 DropDownList、一个 FileUpload 对象和一个用于提交 FileUpload 的按钮。DropDownList 连接到 SqlDataSource,它从我的数据库中的表中查询姓氏,因此 DropDownList 显示所述姓氏。我只是想知道是否可以上传附加到 DropDownList 中值的文件?如果有人想下载特定人上传的文件,以后可以使用它。我已经搜索了很长一段时间,还没有找到任何关于这方面的信息,所以任何帮助将不胜感激。这是我的表单代码:
<p>
Choose student:</p>
<p>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="stulastname"
DataValueField="stulastname">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [stulastname] FROM [application]"></asp:SqlDataSource>
</p>
<p>
Leave comments:</p>
<p>
<asp:TextBox ID="TextBox1" runat="server" Height="159px" Width="482px"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Insert Comments" />
</p>
<p>
Upload comments:</p>
<p>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RegularExpressionValidator id="FileUpLoadValidator" runat="server" ErrorMessage="Upload text documents only" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.txt|.doc)$" ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>
</p>
<p>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Upload File" />
</p>
这是我当前的代码背后的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.IO;
public partial class PS_comments : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.FileName;
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\Assignment\\App_Data\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
con.Open();
con.Close();
cmd = new SqlCommand("UPDATE application SET filename= '" + FileName + "' WHERE stulastname = '" + DropDownList1.SelectedValue + "' ");
cmd.Connection = con;
cmd.ExecuteNonQuery();
string path = Server.MapPath("~/App_Data/userfiles");
bool isExists = System.IO.Directory.Exists(path);
if (!isExists)
System.IO.Directory.CreateDirectory(path);
var file = Path.Combine(path, FileUpload1.FileName);
FileUpload1.SaveAs(file);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\Assignment\\App_Data\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("UPDATE application SET comments = '" + TextBox1.Text + "' WHERE stulastname = '" + DropDownList1.SelectedValue + "' ");
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}