C# - Check If Datareader Is Null Or Has No Rows?

Apr 4, 2011

So I took over this project and one page is throwing a lot of errors. I would need to refactor the whole thing but as always time is an issue.

In one case the code check's whether a datareader has any rows and if not go to an error page. However as the code is now the datareader can be null (didn't successfully connect to db) and in those cases I can't use

if (!dr.HasRows)
//

becasuse it obviously gives me 'nullreferenceexception was unhandled by code'. I tried with !dr.Read but same thing.

A part of the code is something like

SqlDataReader dr = null;
try
{
//connect to db etc
dr = DbHelper.GetReader("sp_GetCustomer", param);
}
catch
{
//show an error message
}
// and then:
if (!dr.HasRows)
{
}

View 2 Replies


Similar Messages:

C# - Check A Datareader For Null?

Feb 10, 2011

I have an aspx page which allows a user to submit modified entries into the database, but when the user clicks Submit to fire the stored procedure I want to first run a check to see if a modified row with the same relationship exists.I am passing the results of the following query:

SELECT SwitchRoom.ModifiedID FROM SwitchRoom WHERE
SwitchRoomID = @ChkSwitchRmID", constring;

into a DataReader to determine if that relationship exists.I need it to determine whether the reader returns NULL to allow the procedure to execute, if it doesn't, then don't allow the user to save the information.I've tried the following:

if (dbreader = NULL)
{
Fire Procedure
}
else
{
"Error Message"
}

and I've even tried passing the reader into a datatable and running it against that without any luck.

View 5 Replies

ADO.NET :: Check For Null Values From DataReader

Feb 16, 2011

I have the following code

public class ProductDetails
{
private string _productid;
public string ProductID
{
get { return _productid; }
}
private string _description;
public string Description
{
get { return _description; }
}
private string _image;
public string Image
{
get { return _image; }
}
public ProductDetails(string productid, string description, string image)
{
_productid = productid;
_description = description;
_image = image;
}
}
public class DataAccess
{
private static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public ProductDetails GetProductDetails()
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
string productid = HttpContext.Current.Request.QueryString["productid"];
cmd.Parameters.Add(new SqlParameter("productid", SqlDbType.NVarChar)).Value = productid;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
ProductDetails pro = new ProductDetails(
(string)reader["ProductID"], (string)reader["Description"], (string)reader["Image"]);
reader.Close();
return pro;
}
}
protected void PopulateControls()
private DataAccess da = new DataAccess();
{
ProductDetails product = da.GetProductDetails();
if (product.Description == String.Empty)
{
lblDescription.Visible = false;
}
else
{
lblDescription.Text = product.Description;
}
}

In the last piece i want to check if the Description field is null or empty in order to hide the label control but i get an error if i write: if (product.Description == DBNull.Value) and can only use ring.Empty. But i want to check for NULL values as well..

View 3 Replies

Datareader Vs Dataset - Get The Number Of Rows From The Datareader?

Nov 15, 2010

I'm having a method that exports content from the database to excel files. The method taks as paramaters a DataReader param and a int param - the number of rows. For the number of rows i'm using a dataset, wich i fill using the same query as for the datareader. So I'm executing it twice... Is there a way I can avoid that? get the number of rows from the datareader?

View 1 Replies

Forms Data Controls :: Expand And Collapse Grid Rows + Check Box For Selecting Rows?

Mar 21, 2011

I have been handling everything in code which is not working consistently same in all scenarios.

View 1 Replies

MVC :: Can Access Data.rows.length In All Browsers But In Chrome Data.rows Is Null

Feb 22, 2011

I have an Ajax call as below

[code]....

I can access data.rows.length in all browsers but In chrome data.rows is null

View 2 Replies

C# - Already An Open DataReader Associated With This Command - When I'm Not Using Datareader

Jul 28, 2010

I am getting an error that an open DataReader associated with this Command, when I'm not using datareader(though probably executereader() is the same thing) how would I close this if I don't have a datareader present?

using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("spSelectAllTypes",conn);
cmd.CommandType = CommandType.StoredProcedure;
[code]...

I just want to be able to databind a bunch of dropdownlist in one open connection. (before I had multiple open and closes for each control)

View 2 Replies

Lambda Check For Null?

Mar 29, 2011

var pq = attributes.SingleOrDefault(a => a.AttributeName == PasswordQuestion").AttributeValue;

The above code will throw an error if null. What is the best way to handle this?The below code would work, but I can't help but feel there's a more graceful way?

var pq = (attributes.SingleOrDefault(a => a.AttributeName == "PasswordQuestion") != null) ? attributes.SingleOrDefault(a => a.AttributeName == "PasswordQuestion").AttributeValue : null;

View 1 Replies

ADO.NET :: How To Check If ExecuteScalar() Is Null

Oct 21, 2010

I know for a fact that the SQL statement below returns NULL but my code statement "if (obj != null)" is not working.When I debug it I see a value of {} ... not sure what that is. Here is my code:

[Code]....

So, even if SQL returns NULL, it still validates obj as NOT NULL !

View 3 Replies

How To Check Null EventArgs

Feb 11, 2010

I have Sub that requires EventArgs as below.

Sub Testing(ByVal sender As Object, ByVal e As EventArgs)

If I want to call the Sub from PageLoad event, I wrote like this Testing(nothing,nothing)

Then, in the Sub, I would like to check If Argment is Nothing or not

Dim testID As String
If (CType(sender, LinkButton).CommandArgument) = Nothing
testID=Request.QuerySting("myID")
ELSE
testID=(CType(sender, LinkButton).CommandArgument).ToString
End If

I get Null error at if statement (If (CType(sender, LinkButton).CommandArgument) = Nothing)

View 1 Replies

Check For Null With HtmlAgilityPack?

Apr 4, 2011

How do you check for null with HtmlAgilityPack? I'm getting "Property or indexer 'HtmlAgilityPack.HtmlNode.HasChildNodes' cannot be assigned to -- it is read only" with the following.

if (Node.Element("TD").HasChildNodes = DBNull.Value)

I"m getting "Object reference not set to an instance of an object. " with

if (Node.Element("TD").HasChildNodes)

View 1 Replies

Web Forms :: Check Whether Session Is Null?

Aug 27, 2013

If i have a page in which I want to check whether session is null.

If it is null it will redirect to other page.

But i also have a   if (!Page.IsPostBack)

so i will check the session inside this   if (!Page.IsPostBack) or outside it?

View 1 Replies

DataTable.Rows.Find Returns Null

Feb 13, 2010

I have a DataTable for which a PrimaryKey constraint has been set to be a combination of an integer column and a datetime column. When I try to 'Find' a row by saying,

dtFunds.Rows.Find(iContainerIndex)

I get a null value. iContainerIndex has been defined as an object array of size 2 with the integer ID and date values in it.

When I set a breakpoint in my code, I see that the very same values are present in the datatable.

If I try to execute, DataTable.Select() method with the integer column filter, I get a result - but returns no result when called with the date column filter.

What am I doing wrong here? The very same DateTime value is present in the datatable.

View 1 Replies

ADO.NET :: How To Check If The Tables Has Rows In Linq

Nov 23, 2010

I am very new to Linq , i want to check if the PrintingAdminSetting table has rows in it and then if it has then i want to get the value and assign it to txtMaxJobs textbox

below is teh code

, please let me know teh syntax to check .

var DC = new ServiceDataContext();
var rec = DC.PrintingAdminSetting.Where("").First();
txtMaxJobs.Text = rec.ParaName.ToString();

View 4 Replies

C# - Check Whether Datatable Contains Any Matched Rows?

Aug 11, 2010

I am using Compute for summing up a datatable which has a condition. Sometimes, there are no rows inside the datatable matching my criteria so I get an exception on ComputeObject cannot be cast from DBNull to other types.Is there a way to check/filter the datatable to see if it has the desired rows, if yes only then I apply Compute.

total = Convert.ToDecimal(CompTab.Compute("SUM(Share)", "IsRep=0"));

View 2 Replies

Check If Output Parameter Is Null Before Binding?

Jan 26, 2011

How can i check if an output parameter is null before i bind it to a asp literal, and if it is null i want to just make the literal

hname1.Text = cmd.Parameters("@hotel1").Value
hname1.DataBind()
hname2.Text = cmd.Parameters("@hotel2").Value

[code]...

View 1 Replies

Web Forms :: How To Check Whether The Int Parameter Is Empty Or Null

Aug 17, 2010

I have set the value of an int parameter to the attribute of a textbox.The textbox can be empty or null, how to check whether the parameter is empty or null?

View 5 Replies

Access :: C# - How To Check Image Field Is Null Or Not

Mar 28, 2011

Actually i have a table with 7 columns

1) Title varchar(100)

2)Description varchar(300)

3)ProfilePicture varbinary(max)

4) Image1 varbinary (max)

5)Image2 varbinary(max)

6)Image3 varbinary(max)

7)Image4 varbinary(max)

Image1,2,3,4 are not a mandatory fields so, when i inserted, i check it if it is not there then i insert null value, Now problem is when i retrive them if there is a row contain image1,2 are image content and 3,4 are null values dataset also filling as it is in database but when i checking like

[code]....

it shows error like

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

View 3 Replies

SQL Server :: In Sql Function Check To See If Variable Is Null?

Feb 4, 2011

Inside a function I need to check to see if a variable value is null, how to do this? I implemented the code but its not returning the value I thought it would return.If it's null I want to set the value of the variable, else I want to query the value from a table

[Code]....

View 5 Replies

ADO.NET :: Check If Statement Is Null In Linq Sql, Then Continue?

Mar 12, 2011

Right now I have an error if f.ParentID is null:

DataSet1.TreeItemRow[]
TreeItemRows = (from f
in tidt
where (f.ParentID == TreeItemId)
select f).ToArray();

I must continue if f.ParentID is null, I don't want to include null fileds in the array. What is the right syntax for that is linq sql?

View 17 Replies

Web Forms :: Check If QueryString Parameter Has Value Or It Is NULL In C#

Jun 25, 2012

How to check the query string value null, if null then display the default value instead of object reference error.

View 1 Replies

SQL Server :: Desired Rows Not Returned Because Of Null Values

Sep 26, 2010

I have a property table and an image table.

I want this query to return all distinct properties and a thumbnail image. However some properties don't have thumbnail images and they don't get returned by the query. If the imgid is null I still want to return the property. Not sure of how to do this.

[Code]....

[Code]....

View 4 Replies

Forms Data Controls :: How To Handle Null Rows

Jun 18, 2010

I have a query that averages data in 15 minute increments that I display in a chart using Microsoft Chart Controls. Everything works fine except when there is no data for a 15 minute increment. How do I get the chart to show just the empty time slot?

Query:

[Code]....

View 4 Replies

Check For A Null Object Reference When Validating Forms In MVC?

May 28, 2010

I'm experimenting with validating forms in the asp.net MVC framework. I'm focusing on server side validation for the time being. I've come across an error that I'm not sure how to rectify. System.NullReferenceException: Object reference not set to an instance of an object. The code that throws the error is:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="ID")] MembersCreate mc )
{
mc.Modules = ModuleListDataContext.GetModuleList();
ViewData.Model = mc;
//Validation using ModelState
//
//
//line below errors when form field is empty
//
if ((string)mc.Member.Username.Trim() == "")
ModelState.AddModelError("Member.Username", "Username is required.");
if (!ModelState.IsValid)
return View();
try
{
// TODO: Add insert logic here
return RedirectToAction("Index","Home");
}
catch
{
return View();
}
}

When I put spaces in the field it performs exactly as i want, but if I leave the field blank and press submit I get the error. What's the best way to avoid this error and still validate blank form fields?

View 1 Replies

DataSource Controls :: How To Check For Both Empty And Null Fields

Jan 28, 2010

How do I check if my value is empty AND Isnull? I need to check for both, using ISNULL is not enough because the data can change just so that it is empty.

how I can change my query to accommodate this?

[Code]....

View 5 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved