Gridview未选择图像会出错

时间:2015-04-18 14:02:28

标签: c# asp.net gridview file-upload

我有一个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);
            }
        }
    }

请建议做什么

1 个答案:

答案 0 :(得分:0)

是的,您可以为上传控件添加customvalidator并在那里添加验证逻辑。如果您希望在回发之前完成该操作,您可以编写一个简单的javascript验证函数并将其分配给customvalidator的ClientValidationFunction属性。

aspx页面中的这类内容应该可以完成,请注意我还没有测试过它:

    <asp:CustomValidator ID="cv" runat="server" Display="Dynamic" ControlToValidate="imageFile"             
ErrorMessage="Please select file to upload." ValidateEmptyText="True" SetFocusOnError="true"
    ClientValidationFunction="ValidateUploadedFile">
    </asp:CustomValidator>

    <script language="javascript"> 
       function ValidateUploadedFile(source, arguments) { 
            var path = document.getElementById('<%= imageFile.ClientID %>').value;
            if (path != "")
            {
                arguments.IsValid = true;
            }       
            else
            {
                arguments.IsValid = false;
            }
        }
    </script>