Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am checking
whether record exist in database or not
, but getting error as
Object reference not set to an instance of an object.


Actually what happen if record exist in databse it give message but when not exist it give error

What I have tried:

string time = DateTime.Now.Day.ToString();
      SqlConnection con5 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
      con5.Open();
      SqlCommand check_User_Name = new SqlCommand("select * from attendance where date= convert(varchar(11), getdate(), 105) and name=@name", con5);
      check_User_Name.Parameters.AddWithValue("@name", DropDownList1.Text);


      int UserExist = (int)check_User_Name.ExecuteScalar();

      if (UserExist > 0)
      {
          ShowPopUpMsg("Already Saved Today!!");
           DropDownList12.Enabled=false;
      }
      else
      {
          if (time == "12")
          {
              DropDownList12.Enabled = true;
          }
      }

      con5.Close();
Posted
Updated 11-Jan-18 19:00pm

replacing * with count(1) would have fixed your issue
SQL
select count(1) from attendance where date= convert(varchar(11), getdate(), 105) and name=@name
 
Share this answer
 
Try This :

string query="select * from attendance where date= convert(varchar(11), getdate(), 105) and name=@name";

if(IsExist(query))
{
  // Recored Exist
}

 public bool IsExist(string Query)
        {
            bool check = false;
            using (cmd = new SqlCommand(Query, con))
            {
                con.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                if (sdr.HasRows)
                    check = true;
            }
            sdr.Close();
            con.Close();
            return check;

        }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900