简体   繁体   中英

Alert message if data is existed in MS ACCESS DB using c#

OleDbCommand cmd1 = new OleDbCommand("select * from patient_det", con);
int count = (int)cmd1.ExecuteScalar();
if (count > 0)
{ 
   Response.Write("<script>alert('Data Existed!!')</script>");
}
else
{  
    OleDbCommand cmd2 = new OleDbCommand("insert into patient_det values('" + st1 + "' , '" + i1 + "' , '" + i2 + "' , '" + i3 + "' , '" + p1 + "')", con);
    cmd2.ExecuteNonQuery();
    int temp = cmd2.ExecuteNonQuery();
    Response.Write("<script>alert('Registered Successfully!!')</script>");
} 

This code shows error like

Specified cast is not valid

How to fix it?

The problem is probably in the line:

int count = (int)cmd1.ExecuteScalar();

This is the signature of ExecuteScalar:

public override object ExecuteScalar()

The query "select * from patient_det" using ExecuteScalar will return the element on the first column of the first row of the table so the DataType returned will be the one of the table.

I found Solution for this Question.

    int Count;
    con.Open();
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM TABLENAME WHERE   COLUMNNAME= '" + TXT1.Text + "'", con);
        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        if (dt.Rows.Count == 0)
        {
//Insert Query
           Response.Write("<script>alert('Added Successfully!!')</script>");
         }else
         {
            Response.Write("<script>alert('Data is Exist!!')</script>");

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM