I am trying to create a login form on my ASP.NET website. Currently, there's some problem. I am trying to incorporate the functionality such that the logged in user has the previlige to view only his profile. The code on the login page is this:
business.clsprofiles obj = new business.clsprofiles();
Int32 a = obj.logincheck(TextBox3.Text, TextBox4.Text);
if (a == -1)
{
Label1.Text = "Username/Password incorrect";
}
else
{
Session["cod"]= a;
Response.Redirect("profile.aspx");
}
After logging in, the user is moved to the page where the person can view his profile once logged in. Session is obtaining the value correctly of the logged in person from the login-page and successfully passing it on to the next page. But here on this profile page an error occurs and I think there is problem somewhere in the grid_bind() method below
public void grid_bind()
{
business.clsprofiles obj = new business.clsprofiles();
List<business.clsprofilesprp> objprp = new List<business.clsprofilesprp>();
Int32 z = Convert.ToInt32(Session["cod"]);
objprp = obj.fnd_profiles(z); //This line of code is passing an integer as required but does not get the desired result from the database
GridView1.DataSource = objprp;
GridView1.DataBind();
}
As the error in business logic says, " invalid attempt to read when no data is present in dr"
public List<clsprofilesprp> fnd_profiles(Int32 id)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("fndpro", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
List<clsprofilesprp> obj = new List<clsprofilesprp>();
while(dr.HasRows)
{
clsprofilesprp k = new clsprofilesprp();
k.id = Convert.ToInt32(dr[0]);//Something wrong here?
k.name = dr[1].ToString();
k.password = dr[2].ToString();
k.description = dr[3].ToString();
k.created = Convert.ToDateTime(dr[4]);
k.modified = Convert.ToDateTime(dr[5]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
con.Close();
return obj;
}lesprp k = new clsprofilesprp();
k.id = Convert.ToInt32(dr[0]);//Something wrong here?
k.name = dr[1].ToString();
k.password = dr[2].ToString();
k.description = dr[3].ToString();
k.created = Convert.ToDateTime(dr[4]);
k.modified = Convert.ToDateTime(dr[5]);
obj.Add(k);
}
dr.Close();
cmd.Dispose();
con.Close();
return obj;
You have to call DataReader.Read to fetch the result:
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
// ...
DataReader.Read returns a boolean, so if you have more than 1 result, you can do:
While (dr.Read())
{
// read data for each record here
}
Moreover, you're trying to access the dr data when there's none in this part of the code:
k.id = Convert.ToInt32(dr[0]);//Something wrong here?
k.name = dr[1].ToString();
k.password = dr[2].ToString();
k.description = dr[3].ToString();
k.created = Convert.ToDateTime(dr[4]);
k.modified = Convert.ToDateTime(dr[5])
You've got a problem with...
while (dr.HasRows)
{
/* If this loop is entered, it will run
* indefinitely until the datareader miraculously
* loses all its rows in a hole somewhere */
}
This will either never enter, or will create an infinite loop... it's either got no rows or it has rows. What I think you meant was:
while (dr.Read())
{
/* Do something with the current record */
}
dr.Read() loops to the next record and returns true or false depending on if there's a record to be read or not. When the data reader is initialized, the first record is not selected. It has to be selected by calling dr.Read() which will then return true if a first row is found, and indeed will return true until Read() is called when currently on the last row - i.e. there's no more rows left to read.
dr.HasRows is just a property that tells you if the datareader contains rows... which if it does will keep having rows from here until eternity. For instance, you would use this if you wanted to do something in the event it has rows and something else in the event it doesn't:
if (dr.HasRows)
{
while (dr.Read())
{
/* Display data for current row */
}
}
else
{
Console.WriteLine("I didn't find any relevant data.");
}
You are trying to access a row in the datareader though there are no rows. i.e
if the dr doesn't enter the while loop then there are no rows in the datareader, however you are still accessing the fields where you have a comment "//Something wrong here? ".
Related
Hi i am new here i just want to ask question for this code.
i am making a condition on my new buttom that generate Enumber= Employee Number.
i have database but no data record yet. if i press my new buttom my sql statement will select he last record on my data but i don't have yet data so i am trying to make a condition.
if Enumber is empty in database it should return and give the new Enumber on my textbox = txtEnumber.Text = "100000".
i hope you understand my problem.
con.Open();
cmd = new SqlCommand("SELECT TOP 1 Enumber FROM Employee ORDER BY Enumber DESC ", con);
dr = cmd.ExecuteReader();
dr.Read();
if (dr["Enumber"] == null) // Error: "Invalid attempt to read when no data is present."
{
txtEnumber.Text = "100000";
return;
}
else
{
String a = dr["Enumber"].ToString();
txtEnumber.Text = ("");
for (int i = 0; i < 1; i++)
{
string val = a.Substring(1, a.Length - 1);
int newnumber = Convert.ToInt32(val) + 1;
a = newnumber.ToString("100000");
}
txtEnumber.Text = a;
}
con.Close();
Since you don't have any row in your case, you can't iterate your reader. Instead of that, you can use ExecuteScalar which returns null as an object if there is no data in first column of the first row since your query returns as SELECT TOP 1...
var result = cmd.ExecuteScalar();
if(result == null)
{
txtEnumber.Text = "100000";
}
You should check whether there are rows first. dr.Read() returns whether the DataReader has rows, use it.
Your DataReader returns no results...
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
// read data for first record here
}
If you have more than one result, use a 'while' loop.
while (dr.Read()) {
// read data for each record here
}
You should use dr.HasRows to check whether there is data or not.
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
dataTable.Load(dr);
}
If you have more than one result, use a 'foreach' loop.
foreach (DataRow Drow in datatable.Rows)
{
// read data for each record here
}
Try This is Worked..
private void button1_Click(object sender, EventArgs e)
{
string name;
name = textBox5.Text;
SqlConnection con10 = new SqlConnection("con strn");
SqlCommand cmd10 = new SqlCommand("select * from sumant where username=#name");
cmd10.Parameters.AddWithValue("#name",name);
cmd10.Connection = con10;
cmd10.Connection.Open();//line 7
SqlDataReader dr = cmd10.ExecuteReader();
}
if ( textBox2.Text == dr[2].ToString())
{
//do something;
}
When I debug until line 7, it is OK, but after that dr throws an exception:
Invalid attempt to read when no data is present.
I don't understand why I'm getting that exception, since I do have data in the table with username=sumant.
Please tell me whether the 'if' statement is correct or not. And how do I fix the error?
You have to call DataReader.Read() to fetch the result:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read())
{
// read data for single/first record here
}
DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:
while (dr.Read())
{
// read data for each record here
}
You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.
I just had this error, I was calling dr.NextResult() instead of dr.Read().
I would check to see if the SqlDataReader has rows returned first:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
I used the code below and it worked for me.
String email="";
SqlDataReader reader=cmd.ExecuteReader();
if(reader.Read()){
email=reader["Email"].ToString();
}
String To=email;
I was having 2 values which could contain null values.
while(dr.Read())
{
Id = dr["Id"] as int? ?? default(int?);
Alt = dr["Alt"].ToString() as string ?? default(string);
Name = dr["Name"].ToString()
}
resolved the issue
private void button1_Click(object sender, EventArgs e)
{
string name;
name = textBox5.Text;
SqlConnection con10 = new SqlConnection("con strn");
SqlCommand cmd10 = new SqlCommand("select * from sumant where username=#name");
cmd10.Parameters.AddWithValue("#name",name);
cmd10.Connection = con10;
cmd10.Connection.Open();//line 7
SqlDataReader dr = cmd10.ExecuteReader();
}
if ( textBox2.Text == dr[2].ToString())
{
//do something;
}
When I debug until line 7, it is OK, but after that dr throws an exception:
Invalid attempt to read when no data is present.
I don't understand why I'm getting that exception, since I do have data in the table with username=sumant.
Please tell me whether the 'if' statement is correct or not. And how do I fix the error?
You have to call DataReader.Read() to fetch the result:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read())
{
// read data for single/first record here
}
DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:
while (dr.Read())
{
// read data for each record here
}
You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.
I just had this error, I was calling dr.NextResult() instead of dr.Read().
I would check to see if the SqlDataReader has rows returned first:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
I used the code below and it worked for me.
String email="";
SqlDataReader reader=cmd.ExecuteReader();
if(reader.Read()){
email=reader["Email"].ToString();
}
String To=email;
I was having 2 values which could contain null values.
while(dr.Read())
{
Id = dr["Id"] as int? ?? default(int?);
Alt = dr["Alt"].ToString() as string ?? default(string);
Name = dr["Name"].ToString()
}
resolved the issue
I have a C# application that submits information to an Access database. I fill in three required boxes , and click "Submit". The script should respond in the following manner when the use clicks the button:
Step 1. Look into database Table A, to see if the value in textBox1 exists in the database.
Step 2. If the value exists, add the values of textBox1, textBox2, and textBox3 into database Table B columns, respectively.
Step 3. If any one of the three text boxes are left blank, display a message.
Step 4. If the value in textBox1 is not in the database table, display a message. (eventually, I plan the replace the message with a default population of the database fields)
THE PROBLEM: When I run the program, in any of the above cases, the result is Step number 4 above. It seems to skip the first "if" statement, and jumping right to the "else" outcome.
Any help resolving this, would be greatly appreciated! The "Private Void "code is below.
Thanks in advance.
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("select * from script_Orders where cust_Name = #UserID", vcon);
OleDbParameter param = new OleDbParameter();
param.ParameterName = "#UserID";
param.Value = textBox1.Text;
cmd.Parameters.Add(param);
OleDbDataReader reader = cmd.ExecuteReader();
{
if (reader.HasRows)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("You must fill in all fields.");
return;
}
else
{
OleDbCommand dbCommand;
OleDbDataReader dbReader;
new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Search\Database.accdb");
dbCommand = new OleDbCommand("select count(*) as Record_Count from script_received", vcon);
dbReader = dbCommand.ExecuteReader();
if (dbReader.Read() == true)
rowCount = dbReader["Record_Count"].ToString();
else
return;
var date = DateTime.Now.ToString("MM/dd/yyyy");
{
using (OleDbCommand command = new OleDbCommand("INSERT INTO script_Received (script, qty, emp_id, received_Date) VALUES (#script,#qty,#emp_Id,#rec_date)"))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#script", OleDbType.Integer).Value = textBox1.Text;
command.Parameters.Add("#qty", OleDbType.VarChar).Value = textBox2.Text;
command.Parameters.Add("#emp_id", OleDbType.VarChar).Value = textBox3.Text;
command.Parameters.Add("#rec_date", OleDbType.Date).Value = date;
command.Connection = vcon;
command.ExecuteNonQuery();
}
this.textBox1.Clear();
this.textBox2.Clear();
this.textBox1.Focus();
}
}
}
else
{
MessageBox.Show("The value of textBox1 is not in the orders table");
return;
}
}
}
If it jumps to the else of if(reader.HasRows) without throwing any exceptions, then reader must not be null, and it's HasRows property must be false. That means your query executed successfully but returned no rows.
You might try running the select statement by hand, which might help you understand what's wrong. Most likely, you're typing something in the textbox that doesn't match any of the cust_name values.
My code:
string sqlQuery1 = "select * from employees where depid=6";
SqlDataReader Dr1 = dbconn.RunQueryReturnDataReader(sqlQuery1);
if(Dr1.read()) { //or if (Dr1["empname"] != DBNull.Value)
while (Dr1.Read())
{
Label1.Text = Dr1["empname"].ToString();
Label2.Text = Dr1["empdes"].ToString();
...
}
Dr1.Close();
}
else {
Label1.text = "defaultValue";
Label2.text = "defaultValue";
...
}
I just want to check SqlDataReader has no records to display. If no records ,the labels should showdefault values preassigned by me or If has record display datareader value on label. (Assume either SqlDataReader has 1 recode or has norecord only)
How can I check first datareader hasRow or not?
I have tried two ways as above code.
if(Dr1.read()) - this way working fine. But after execute If statement ,it has no value to display on labels , since read() will increase the pointer. As a result label1 ,Label2.. Nothing display.
if (Dr1["empname"] != DBNull.Value)
This way generate an exception when Sqldatareader has norows.
error: System.InvalidOperationException: Invalid attempt to read when no data is present
Please help me. tx
try...
if(Dr1.HasRows)
{
//....
}
if (Dr1 == null || !Dr1.HasRows) {
// Do something
}