【发布时间】:2015-06-25 10:26:07
【问题描述】:
我有一个gridview,我必须通过FileUpload 选择图像并提交按钮单击,以便将路径和相关信息提交到数据库中。
但是当我将 gridview 保持为空并单击提交按钮时,我收到错误
必须声明标量变量“@img_path”。
我有什么方法可以提供验证,以便用户必须选择图像,然后只提交表单
下面是我的代码:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
foreach (GridViewRow row in ImagesGrid.Rows)
{
var title = row.FindControl("txtTitle") as TextBox;
var description = row.FindControl("txtDescription") as TextBox;
var imageFile = row.FindControl("flUpload") as FileUpload;
var chkDefault = row.FindControl("chkDefault") as CheckBox;
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("Insert into tbl_galleries_stack (gallery_id,img_title,img_desc,img_path,IsDefault) values (@gallery_id,@img_title,@img_desc,@img_path,@IsDefault)", conn);
cmd1.Parameters.Add("@gallery_id", SqlDbType.Int).Value = Convert.ToInt32(ddlgallery.SelectedValue);
cmd1.Parameters.Add("@img_title", SqlDbType.NVarChar).Value = title.Text;
cmd1.Parameters.Add("@img_desc", SqlDbType.NVarChar).Value = description.Text;
if (imageFile.HasFile)
{
imageFile.SaveAs(Server.MapPath("~/GalleryImages/") + imageFile.FileName);
cmd1.Parameters.Add("@img_path", SqlDbType.NVarChar).Value = "~/GalleryImages/" + imageFile.FileName;
}
cmd1.Parameters.Add("@IsDefault", SqlDbType.Bit).Value = chkDefault.Checked;
cmd1.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Gallery images added sucessfully');window.location ='csrgalleriesstack.aspx';", true);
}
}
}
请提出建议
【问题讨论】:
-
我强烈怀疑你的
imageFile.HasFile如果false并且它没有添加这个参数。您是否调试过您的代码并看到它确实将您的代码放入了这个 if 语句中? -
@SonerGönül:是的,我调试了代码,但它仍在内部并给出了我在帖子中提到的错误
标签: c# asp.net gridview file-upload