I have this code that Inserts data to database. I want to check if the ID going to be inserted is already in database. but if it is not in database it should be inserted. But has some errors, can you please help me out with it?
public void Add()
{
sc.Open();
try
{
cmd = new SqlCommand("Select idnum from TableVotersInfo Where idnum=@idnum", sc);
cmd.Parameters.AddWithValue("@idnum", _idnum);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read() == true)
{
MessageBox.Show("ID number already exist!");
rd.Close();
}
else
{
cmd = new SqlCommand("INSERT INTO TableVotersInfo (Education, idnum, FirstName, MiddleName, LastName, SchoolYear, ControlNum, VResult) VALUES (@ed, @idnum, @firstname, @middlename, @lastname, @schoolyear, @controlnum, 'Not Voted');", sc);
cmd.Parameters.AddWithValue("@id", _id);
cmd.Parameters.AddWithValue("@ed", _ed);
cmd.Parameters.AddWithValue("@idnum", _idnum);
cmd.Parameters.AddWithValue("@firstname", _firstname);
cmd.Parameters.AddWithValue("@middlename", _middlename);
cmd.Parameters.AddWithValue("@lastname", _lastname);
cmd.Parameters.AddWithValue("@schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("@controlnum", _controlnum);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Stored Successfully!");
FAddVoters._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
Edit
My error now is There is already an open DataReader associated with this command which must be closed first.
.
Update
public void Update()
{
sc.Open();
try
{
cmd = new SqlCommand("UPDATE TableVotersInfo SET Education=@ed, idnum=@idnum, FirstName=@firstname, MiddleName=@middlename, LastName=@lastname, SchoolYear=@schoolyear, ControlNum=@controlnum WHERE id=@id", sc);
cmd.Parameters.AddWithValue("@id", _id);
cmd.Parameters.AddWithValue("@ed", _ed);
cmd.Parameters.AddWithValue("@idnum", _idnum);
cmd.Parameters.AddWithValue("@firstname", _firstname);
cmd.Parameters.AddWithValue("@middlename", _middlename);
cmd.Parameters.AddWithValue("@lastname", _lastname);
cmd.Parameters.AddWithValue("@schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("@controlnum", _controlnum);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("Successfully Updated!");
FAddVoters._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}