Chetan Sarode Chetan Sarode - 2 months ago 11
ASP.NET (C#) Question

Prevent to insert the blank row in table

I have html table with 4 row when all row have data it insert all record to database as i want, but when only 1 or 2 row have data then also it inserting the 4 rows to database like 2 with data and 2 rows blank.i need to prevent the black row insertion to database..How to Solve..Thanks in advance..

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;
}
}

Answer

Why can't you simply check if it's empty, for example:

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);
}

Maybe you want to use String.IsNullOrWhiteSpace or you want to check all strings. It's just an example. But apart from that, you should do validation via ASP.NET validators. If the field is mandatory you should use a RequiredFieldValidator.

Comments