防止在表中插入空白行

本文关键字:插入 空白 | 更新日期: 2023-09-27 18:06:53

我有4行的html表,当所有行都有数据时,它将所有记录插入到我想要的数据库,但当只有1或2行有数据时,它也将4行插入到数据库,如2行数据和2行空白。我需要防止黑行插入数据库..如何解决..提前感谢..

 protected void btnSubmit_Click(object sender, EventArgs e)
        {
            DataTable Dt = new DataTable();
            Dt.Columns.Add("StudentName");
            Dt.Columns.Add("RegistrationNumber");
            Dt.Columns.Add("Department");
            Dt.Columns.Add("FatherName");
       for (int i = 1; i <= 4; i++)
            {
                string StudentName = Request.Form["name" + i].ToString();
                string RegistrationNumber = Request.Form["reg" + i].ToString();
                string Department = Request.Form["dep" + i].ToString();
                string FatherName = Request.Form["Fname" + i].ToString(); 
                Dt.Rows.Add(StudentName, RegistrationNumber, Department, FatherName);

            }
            string cs = ConfigurationManager.ConnectionStrings["DUM"].ConnectionString;
            SqlConnection con = new SqlConnection(cs);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "InsertStudentDetails";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@DetailInsersion", Dt);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                lblStatus.Text = "Details Saved into Database";
            }
            catch (Exception es)
            {
                throw es;
            }
            }

防止在表中插入空白行

为什么不能直接检查它是否为空,例如:

for (int i = 1; i <= 4; i++)
{
    string StudentName = Request.Form["name" + i].ToString();
    if(String.IsNullOrEmpty(StudentName))
        continue;
    string RegistrationNumber = Request.Form["reg" + i].ToString();
    string Department = Request.Form["dep" + i].ToString();
    string FatherName = Request.Form["Fname" + i].ToString(); 
    Dt.Rows.Add(StudentName, RegistrationNumber, Department, FatherName);
}

也许你想使用String.IsNullOrWhiteSpace或者你想检查所有的字符串。这只是一个例子。但除此之外,您应该通过ASP进行验证。净验证器。如果字段是强制性的,您应该使用RequiredFieldValidator

在添加为行之前检查您的输入

for (int i = 1; i <= 4; i++) {
    // read from form into string variables ...
    var doWriteToDb = !string.IsNullOrWhiteSpace(StudentName)
                   || !string.IsNullOrWhiteSpace(RegistrationNumber)
                   || !string.IsNullOrWhiteSpace(Department)
                   || !string.IsNullOrWhiteSpace(FatherName);
    if (doWriteToDb) {
        Dt.Rows.Add(StudentName, RegistrationNumber, Department, FatherName);
    }
}

使用以下代码。我希望它能帮助你。

public bool IsValid {
    get {
        return !string.IsNullOrEmpty(StudentName) &&
               !string.isNullOrEmpty(your other field)...;
        // I'm just guessing here what controls your form has. you should see the point though
    }
}