Error is trying to read when no Data present. Here is the source code:
public partial class FormUser : Form
{
static string initString = "Data Source=Odin\\SQLExpress; Persist Security Info=False;User ID=sa;"
+ "password=1ntelPWD!;Initial Catalog=membership"; DataSet dsUser = new DataSet();
SqlConnection cs = new SqlConnection(initString);
SqlDataAdapter daUser = new SqlDataAdapter();
BindingSource tblContactBS = new BindingSource();
private void getLoggedOnID()
{
dsUser.Clear();
try
{
string s2 = tBoxUID.Text;
string s1 = "SELECT * FROM tbUser WHERE UID = \'" + s2 + "\'";
MessageBox.Show("s1 = " + s1);
SqlCommand cmd = new SqlCommand(s1, cs);
cs.Open();
SqlDataReader reader = cmd.ExecuteReader();
usr.LoggedOnID = reader.GetInt32(0);
usr.UID = reader.GetString(1);
usr.PWD = reader.GetString(2);
usr.PWDHint = reader.GetString(3);
usr.DisplayName = reader.GetString(4);
usr.Email = reader.GetString(5);
usr.IsLoggedOn = true;
reader.Close();
cs.Close();
Sam HobbsPosted Mar 21, 2024, 6:06 PM
Programmers do not like to check for errors but we need to. Your
cs.Open();should be done intry ... catchblocks. Just to be sure everything is working, you can check to ensure thatcs.StateisSystem.Data.ConnectionState.Open. Also many programmers will say to useSqlDataReaderin ausingblock. Others have answered the question about why you are getting the current error.Naimish MakwanaPosted Mar 21, 2024, 1:08 PM
The error message “trying to read when no Data present” is likely due to the fact that the SQL query did not return any data. In your code, you’re trying to read data from the
SqlDataReaderwithout checking if there are any rows returned by the query.You can avoid this error by checking if there are any rows in the
SqlDataReaderbefore trying to read data. Here’s how you can modify your code:This code checks if the
SqlDataReaderhas any rows using theHasRowsproperty. If it does, it reads the data. If not, it shows a message saying “No data found for the given UID”. This should prevent the error you’re seeing. Please replace theMessageBox.Show("Error: " + ex.Message);with your own error handling logic. Remember, it’s always a good practice to handle exceptions that might occur during database operations.Thanks
Jignesh KumarPosted Mar 21, 2024, 8:03 AM
Check reader has data or not using HasRows property,