当所有行都有数据时我有4行的html表它按照我的意愿将所有记录插入到数据库中,但是当只有1或2行有数据时,它也将4行插入数据库,如2,数据和2行blank.i需要阻止黑行插入数据库。如何解决..提前谢谢..
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;
}
}
答案 0 :(得分:1)
为什么不能简单地检查它是否为空,例如:
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.NET validators进行验证。如果该字段是必填字段,则应使用RequiredFieldValidator
。
答案 1 :(得分:0)
在将输入添加为行之前检查输入。
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);
}
}
答案 2 :(得分:0)
您使用此代码。我希望它可以帮助您。
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
}
}