如何在保存到数据库之前检查单元格是否为空

时间:2013-05-27 07:15:07

标签: datagridview

嗨我有3个columnes的agrid视图我想检查第2列& 3是空显示消息,说在执行保存代码之前但我不能这样做是我保存的代码

        //second part
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            condatabase.Open();

            string Query1 = "insert into mal_makbodatsandok_det (ERADID,ERADTYPENAME,BAYAN,MONY) values('"+txtID.Text+"','" + this.dataGridView1.Rows[i].Cells[1].Value + "','" + this.dataGridView1.Rows[i].Cells[2].Value + "','" + this.dataGridView1.Rows[i].Cells[3].Value + "') ;";


            SqlCommand cmddatabase = new SqlCommand(Query1, condatabase);
            myreader = cmddatabase.ExecuteReader();

            while (myreader.Read())
            {

            }

            condatabase.Close();
    }

        MessageBox.Show("saved");  

有人告诉我如何在保存之前检查

2 个答案:

答案 0 :(得分:1)

尝试类似的东西

if (dataGridView1.CurrentCell.Value == DBNull.Value)
{
    MessageBox.Show("null");
}
else
{
    MessageBox.Show("not null");
}

希望它有效。

答案 1 :(得分:0)

插入前调用方法

  if(ValidateGridView() != -99)
  {
    //Insert Logic
  }
  else
  {
    //display error message
  }



    private int ValidateGridView()
    {
         for (int i = 0; i < dataGridView1.Rows.Count; i++)
         {
             if(this.dataGridView1.Rows[i].Cells[1].Value != string.Empty && 
         this.dataGridView1.Rows[i].Cells[2].Value != string.Empty && 
         this.dataGridView1.Rows[i].Cells[3].Value != string.Empty)
             {}
             else
             {
             return i; 
                 //Return line number and display message, fields on this row number can not be empty
             }
         return -99; //if return is -99 means no row has empty value

         }
   }