Get all the rows from query result - c#

I have a stored procedure that returns a boolean. (0 or 1). It returns multiple rows. my question is how to iterate through all the result.
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("Reader.usp_CheckerIsStopped", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#fld_UserID", SqlDbType.Int).Value = this.UserID;
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.Read() == 1)
{
return true;
}
else
{
return false;
}
}
}
It has a error in dr.Read() == 1
Error:
Operator == cannot be applied to type bool to int"
My stored procedure returns multiple rows containing 0 or 1,I want to get those values because I want to do a checking if it is equals to true of false (0 or 1)
if (e.Row.RowType == DataControlRowType.DataRow)
{
//if (e.Row.Cells[11].Text == "In Progress")
//{
// System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StartImageButton");
// StartImageButton.Visible = false;
//}
gvfunct.UserID = Convert.ToInt32(Session["UserID"]);
gvfunct.CheckIsStopped();
if (gvfunct.CheckIsStopped() == true)
{
System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].FindControl("StartImageButton");
StartImageButton.Visible = true;
System.Web.UI.WebControls.ImageButton StopImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StopImageButton");
StopImageButton.Visible = false;
}
else
{
System.Web.UI.WebControls.ImageButton StopImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[1].FindControl("StopImageButton");
StopImageButton.Visible = true;
System.Web.UI.WebControls.ImageButton StartImageButton = (System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].FindControl("StartImageButton");
StartImageButton.Visible = false;
}
}

You'll need to continue to Read() and do something with those results.
while (dr.Read())
{
}
You see, the Read() method returns a bool. So, now if you wanted to get to the results of each row you might do something like this:
while (dr.Read())
{
var val = dr.GetInt32(0);
}
and that would get the value of the first column, from the row you're currently on in the Read(), and cast it as an int. Of course that line could throw an error if you're trying to cast a string or something. Consider the fact that a DataReader is a read-only, forward-only, buffer of data. It literally only pulls one row of data at a time from the server, thus leaving the connection open during the duration of the Read() operation and until it goes out of scope.

As dr.Read() returns bool thus you are getting error when comparing with int
It will return true if SqlDataReader has rows otherwise false.
So change you code as
return dr.Read();
instead of
if (dr.Read() == 1)
{
return true;
}
else
{
return false;
}

Replace
if (dr.Read() == 1)
{
return true;
}
with
if (dr.Read())
{
return true;
}

you need to explicitly cast it or just use it's proper Boolean type
so instead of if (dr.Read() == 1), you may use if (dr.Read() == true) or if (dr.Read())
there isn't a direct cast that i am aware of, for instance (bool)1 is not going to work, but you may always use Convert.ToBoolean(1) or some other methods to convert it
you may also create your own custom casting method
IntToBool (int bool)
{
if(bool == 1) return true;
return false;
}

It's not really clear what your stored procedure returns, but if the first row and first column contains for example an integer, you could also forget the reader and use SqlCommands ExecuteScalar-method like so:
return com.ExecuteScalar() == 1;

If you need to iterate through all the rows, try this
if(dr.Read()){
if(dr.Read()) return true;
else return false;
}
else return false;
This will read dr twice and return true if it finds 2 rows. False if it finds 0 or 1 row.

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

How do I check if the value is already present in the database?

Is there a easier way to check the value entered in the textbox with the field in the database if it is already present or not? Because I find this a little complex. Thanks in advance.
public int method(string a)
{
string str;
int chk = 1;
con = new OracleConnection(constr);
con.Open();
try
{
com = new OracleCommand("select a from table where a='" + a + "'", con);
OracleDataReader dr;
dr = com.ExecuteReader();
if (dr.Read())
{
str = dr["A"].ToString();
if (str == a)
chk = 0;
else
chk = 1;
}
else
chk = 1;
return chk;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
Firstly, don't concatenate. Use parameters. Since you are using oracle that is :name syntax, IIRC. Secondly, you can use ExecuteScalar to be simpler, i.e.
public bool RecordExists(string a)
{
using(var con = new OracleConnection(constr))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select 1 from table where a=:a";
cmd.Parameters.AddWithValue("a", a);
con.Open();
return cmd.ExecuteScalar() != null; // returns null if no rows
}
}
But frankly, you can also use tools like "dapper" to make it easier:
public bool RecordExists(string a)
{
using(var con = new OracleConnection(constr))
{
return con.Query("select 1 from table where a=:a", new {a}).Any();
}
}
(and yes, I know I didn't even Open() the connection)
You can use Read to decide if you got exact match as the query you have already check if the given value is present in database table. OracleDataReader.Read will return true if you get atleast one row.
if (dr.Read())
return 1;
else
return 0;
Read returns true if there are more rows; otherwise, false, Reference.
You can change the return type of method to bool and simply return result of read;
return dr.Read()

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
}

sqldatareader error

I want to check if the sqldatareader is null or not. So tried the following code:
if (x[k]!= DBNull.Value)
{
box.Text = Convert.ToString(x[k++]);
if ((box.Text) != "")
current[j - 1] = Convert.ToDouble(box.Text);
else current[j - 1] = 0;
box.Enabled = false;
}
However while trying to check the value within the datareader, it throws an error,"invalid attempt to read data when no data is present". How else should i check to see if data is there or not.!! please help. here x is an sqldatareader
SqlDataReader x = cmd.ExecuteReader();
and cmd is a select commnand..
You can use SqlDataReader.HasRows - it is true if at least one row of data is present, alternatively you can read through all results using SqlDataReader.Read();
So for your example:
while(x.Read())
{
//read stuff
}
You can do a null check and Has Row before accessing the DataRows.
like this
if(null != x && x.HasRows)
{
//Your code
}

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