Here is my code in c#, it is saying “No data exists for the row/column.”, how can I improve this code to make it work properly?
db = new OleDbConnection();
db.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + fileName;
db.Open();
string sql = "SELECT * FROM GroupNameNS WHERE GroupName = '" + Groupnametxt.Text.Trim() + "'";
cmd = new OleDbCommand(sql, db);
rdr = cmd.ExecuteReader();
if (Groupnametxt.Text.Trim() == (string)rdr["GroupName"])
{
MessageBox.Show("Group Name taken, please try another name", "Error in Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
membernumber1.ReadOnly = true;
}
else
{
sql = "INSERT INTO GroupNameNS VALUES ('" + Groupnametxt.Text.Trim() + "')";
membernumber1.ReadOnly = false;
cmd = new OleDbCommand(sql, db);
rdr = cmd.ExecuteReader();
}
You need to call .Read() on your Reader object in order to increment through the rows of your result set.
//Note this will return false if there is no more record(s) to be read, so it is usually used inside and
ifstatement orwhileloopYou could change your
if (Groupnametxt.Text.Trim() == (string)rdr["GroupName"])toif(rdr.Read())because if there is at least 1 record in your table that has thisGroupNamevalue, it will return true.I modified a couple other things too: don’t forget to close your Reader object after using it. And use
ExecuteNonQuery()for anINSERT