您好 任何人都可以帮助我:)。
这段代码中的问题是什么?
protected void LinkButton1_Click(object sender, EventArgs e)
{
//object o = new object();
//Control co = new Control();
//co = GridView1.FindControl("EmpFileUpload");
FileUpload f = new FileUpload();
(System.Web.UI.WebControls.FileUpload)f = (System.Web.UI.WebControls.FileUpload)(GridView1.FindControl("EmpFileUpload"));
if (f.HasFile)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["schoolsConnectionString"].ConnectionString);
conn.Open();
SqlCommand insertCommand = new SqlCommand("insert_Empimg", conn);
insertCommand.Parameters.Add("Emp_imgPath", SqlDbType.NVarChar, 0).Value =f.FileName;
insertCommand.CommandType = CommandType.StoredProcedure;
insertCommand.ExecuteNonQuery();
conn.Close();
}
}
答案 0 :(得分:1)
首先
FileUpload f = new FileUpload();
(System.Web.UI.WebControls.FileUpload)f = (System.Web.UI.WebControls.FileUpload(GridView1.FindControl("EmpFileUpload"));
如果你在下一行重新分配它,则不需要'新'f
。
FileUpload f = (System.Web.UI.WebControls.FileUpload(GridView1.FindControl("EmpFileUpload"));
其次,您需要检查f
的声音是否为空。
if(f != null && f.HasFile)
答案 1 :(得分:1)
您的FindControl可能无法找到上传控件。
让我们整理一下这段代码..
//You dont need the `new` as you are assigning to the result of `FindControl`
FileUpload f = GridView1.FindControl("EmpFileUpload") as FileUpload;
//Check for null here, this is probably your problem
if (f !=null && f.HasFile)
{
//Using statement takes care of closing our connection and disposing our objects.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["schoolsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand insertCommand = new SqlCommand("insert_Empimg", conn))
{
insertCommand.Parameters.Add("Emp_imgPath", SqlDbType.NVarChar, 0).Value =f.FileName;
insertCommand.CommandType = CommandType.StoredProcedure;
insertCommand.ExecuteNonQuery();
}
}
}
然后我们可以查看为什么找不到它,是否可以粘贴声明EmpFileUpload
答案 2 :(得分:0)
FileUpload f = (System.Web.UI.WebControls.FileUpload)(GridView1.FindControl("EmpFileUpload"));
通过GridView1.FindControl("EmpFileUpload")
查找控件取决于您将file upload
放在grid view
中的位置。请放置aspx
镜头以清楚地识别您放置控件的位置。以正确的方式访问它。