How to get the value of sql (sum) query in textbox? [duplicate] - c#

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

Related

Read and Generate New Enumber

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..

Reader.Read() didn't read any row even though it has 1 row [duplicate]

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

DataReader IndexOutofRangeException was unhandled by user code

I ran into another issue again. I was trying to get data from the database using DataReader but I got the error when i was testing my code. Can anyone help me out? The error occurred at this line:
chkAssess = readAssess[columnName].ToString();
Below is the code snippet:
public string CheckAssess(string emailAddress, string columnName)
{
string chkAssess = "";
SqlDataReader readAssess;
//readAssess = new SqlDataReader();
string MgrAssessQry = "SELECT '"+columnName+"' FROM tblAllUsers";
//MgrAssessQry += " WHERE email ='" + emailAddress + "'";
SqlCommand cmdReadAssess = new SqlCommand(MgrAssessQry, cn);
cn.Open();
readAssess = cmdReadAssess.ExecuteReader();
while(readAssess.Read())
{
// Add the rows
chkAssess = readAssess[columnName].ToString();
}
return chkAssess;
}
try to use column name without ''
select something from table
instead of
select 'something' from table
for security reasons, don't create sql queries in that way (by concatenating strings) - use #parameters instead
2. close the reader at the end
Try this:
public string CheckAssess(string emailAddress, string columnName)
{
string chkAssess = "";
SqlDataReader readAssess;
//readAssess = new SqlDataReader();
string MgrAssessQry = "SELECT #Column_Name FROM tblAllUsers";
SqlCommand cmdReadAssess = new SqlCommand(MgrAssessQry, cn);
cmdReadAssess.Parameters.AddWithValue(new SqlParameter("Column_Name", columnName));
cn.Open();
readAssess = cmdReadAssess.ExecuteReader();
while(readAssess.Read())
{
// Add the rows
chkAssess = readAssess.GetString(0);
}
return chkAssess;
}
You have got several problems here.
Check whether your readAssess has rows like below.
if(readAssess.HasRows)
If it doesn't have rows then trying
chkAssess = readAssess.GetString(0);
would throw this error, as Arrays are index-based.
So your code should be like below
if(readAssess.HasRows)
{
while(readAssess.Read())
{
chkAssess = readAssess.GetString(0);
}
}
Other problem is you need to close both the reader & the connection afterwards.
readAssess.Close();
cn.Close();
Also your code is potentially vulnerable to SQL Injection.
if (reader.HasRows)
{
while (reader.Read())
{
int result = Convert.ToInt32(reader.GetString(0));
Console.WriteLine(result);
}
}
The most important thing is check the query first by executing in SQL Server and see if any result is coming or not.
Secondly based on the type of output you are receiving cast it to that particular data type (important).Mostly everyone is saving the data in varchar so.

Check if a datareader has rows or not in Asp.net

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
}

Invalid attempt to read when no data is present in dr

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? ".

Categories