This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I am having problem with nullpointer. I cant seem to understand why my code is wrong. Any help will be greatly appreciated. This is my code:
protected void Page_Load(object sender, EventArgs e)
{
Product aProd = new Product();
// Get Product ID from querystring
string prodID = Request.QueryString["ProdID"].ToString(); (null pointer occurs at this line. )
prod = aProd.getProduct(prodID);
//Display product details on web form
lbl_ProdName.Text = prod.Product_Name;
lbl_ProdDesc.Text = prod.Product_Desc;
lbl_Price.Text = prod.Unit_Price.ToString("c");
img_Product.ImageUrl = "~\\Images\\" + prod.Product_Image;
//Store the value in invisible fields
lbl_Price.Text = prod.Unit_Price.ToString();
lbl_ProdID.Text = prodID.ToString();
}
These are the code for Product.cs. I still have no idea where my codes went wrong
public class Product
{
string _connStr = ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _prodID = null;
private string _prodName = string.Empty;
private string _prodDesc = ""; // this is another way to specify empty string
private decimal _unitPrice = 0;
private string _prodImage = "";
private int _stockLevel = 0;
// Default constructor
public Product()
{
}
// Constructor that take in all data required to build a Product object
public Product(string prodID, string prodName, string prodDesc,
decimal unitPrice, string prodImage, int stockLevel)
{
_prodID = prodID;
_prodName = prodName;
_prodDesc = prodDesc;
_unitPrice = unitPrice;
_prodImage = prodImage;
_stockLevel = stockLevel;
}
// Constructor that take in all except product ID
public Product(string prodName, string prodDesc,
decimal unitPrice, string prodImage, int stockLevel)
: this(null, prodName, prodDesc, unitPrice, prodImage, stockLevel)
{
}
// Constructor that take in only Product ID. The other attributes will be set to 0 or empty.
public Product(string prodID)
: this(prodID, "", "", 0, "", 0)
{
}
// Get/Set the attributes of the Product object.
// Note the attribute name (e.g. Product_ID) is same as the actual database field name.
// This is for ease of referencing.
public string Product_ID
{
get { return _prodID; }
set { _prodID = value; }
}
public string Product_Name
{
get { return _prodName; }
set { _prodName = value; }
}
public string Product_Desc
{
get { return _prodDesc; }
set { _prodDesc = value; }
}
public decimal Unit_Price
{
get { return _unitPrice; }
set { _unitPrice = value; }
}
public string Product_Image
{
get { return _prodImage; }
set { _prodImage = value; }
}
public int Stock_Level
{
get { return _stockLevel; }
set { _stockLevel = value; }
}
Request.QueryString["ProdID"] is returning null.
So your ToString() call cause a System.NullPointerException
Solution : ensure that your Request.QueryString["ProdID"] call sends you back the correct object, or test the result yourself:
var obj = Request.QueryString["ProdID"];
string prodID = obj == null ? String.Empty : obj.ToString();
Related
i have ran into some problems with my insert function.
i am trying to make my the string listing_ID an auto increment int with no input needed, however when coding for the button submit i included all the inputs for all the other values but not listing_ID , this gave me the error below. below are all the images and these are the codes for the insert function.
public class Carlisting
{
private string _listID = "";
private string _car_model = "";
private string _brand_name = "";
private string _car_description = "";
private string _car_condition = "";
private string _price = "";
private string _inspection_date = "";
string _connStr = ConfigurationManager.ConnectionStrings["roadbnb.mdf"].ConnectionString;
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_listID = listID;
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
public Carlisting()
{
}
public string listing_ID
{
get { return _listID; }
set { _listID = value; }
}
public string car_model
{
get { return _car_model; }
set { _brand_name = value; }
}
public string brand_name
{
get { return _brand_name; }
set { _brand_name = value; }
}
public string car_description
{
get { return _car_description; }
set { _car_description = value; }
}
public string car_condition
{
get { return _car_condition; }
set { _car_condition = value; }
}
public string price
{
get { return _price; }
set { _price = value; }
}
public string inspection_date
{
get { return _inspection_date; }
set { _inspection_date = value; }
}
protected void btn_submit_Click(object sender, EventArgs e)
{
int result = 0;
Carlisting car = new Carlisting(tb_model.Text, tb_brand.Text, tb_description.Text, dl_condition.Text, tb_price.Text, tb_date.Text);
result = car.ListingInsert();
if (result > 0)
{
Response.Write("<script>alert('You have succesfully added listing , PLease wait for approval');</script>");
}
else
{
Response.Write("<script>alert('Error : PLease contact helpdesk');</script>");
}
}
public int ListingInsert()
{
int result = 0;
string queryStr = "INSERT INTO Carlisting(car_model, brand_name, car_description, car_condition , price, inspection_date)"
+"VALUES (#car_model, #brand_name, #car_description, #car_condition, #price, #inspection_date)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#car_model", this.car_model);
cmd.Parameters.AddWithValue("#brand_Name", this.brand_name);
cmd.Parameters.AddWithValue("#car_description", this.car_description);
cmd.Parameters.AddWithValue("#car_condition", this.car_condition);
cmd.Parameters.AddWithValue("#price", this.price);
cmd.Parameters.AddWithValue("#inspection_date", this.inspection_date);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}
Does anyone know how should fix it in order to get the results i wan? Thank you in advance
As per your screenshot, you are getting compilation error. To Fix it, create another constructor. Currently your code want to invoke constructor which does not take listId as parameter.
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
: this(car_model, brand_name, car_description, car_condition, price, inspection_date)
{
_listID = listID;
}
public Carlisting(string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
With above the 1st constructor invokes the another constructor with other required parameters. And for your code, the 2nd constructor will be invoked and you won't have compilation error.
i am trying to make a project for my school. I am trying to read a table where some null values are in an integer column. I've made it an integer but i can't get the null values into the integer.
I've already searched in stackoverflow but none of the answers i could make at my project. Can someone provide me some help, tell me where i have to put the code to make it work again. I just started as programmer.
This is my database conn string + reader:
public static List<Klant> GetAlleklanten()
{
var result = new List<Klant>();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select k.klantid, k.naam, k.adres, k.telefoonnummer, k.woonplaats, k.email, k.wachtwoord, kp.klantpasid from klant k left join klantpas kp on k.klantid = kp.klantid";
SqlCommand selectKamers = new SqlCommand(query, conn);
SqlDataReader reader = selectKamers.ExecuteReader();
while (reader.Read())
{
Klant klant = new Klant((int)reader["klantid"], (string)reader["naam"], (string)reader["adres"], (string)reader["telefoonnummer"], (string)reader["woonplaats"], (string)reader["email"], (string)reader["wachtwoord"], (int)reader["klantpasid"]);
result.Add(klant);
}
reader.Close();
}
return result;
}
klantpasid is the one that also can return a null value instead of an integer.
Here is the class where the klantpasid is in the construtor:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FontysHotel
{
public class Klant
{
// instantie variabelen
private int klantid;
private string naam;
private string adres;
private string telefoonnummer;
private string woonplaats;
private string email;
private string wachtwoord;
private int? klantpasid;
// properties
public int Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
public string Naam
{
get
{
return naam;
}
set
{
naam = value;
}
}
public string Adres
{
get
{
return adres;
}
set
{
adres = value;
}
}
public string Telefoonnummer
{
get
{
return telefoonnummer;
}
set
{
telefoonnummer = value;
}
}
public string Woonplaats
{
get
{
return woonplaats;
}
set
{
woonplaats = value;
}
}
public string Email
{
get
{
return email;
}
set
{
email = value;
}
}
public string Wachtwoord
{
get
{
return wachtwoord;
}
set
{
wachtwoord = value;
}
}
public int? Klantpasid
{
get
{
return klantpasid;
}
set
{
klantpasid = value;
}
}
// Constructor
public Klant(int klantid, string naam, string adres, string telefoonnummer, string woonplaats, string email, string wachtwoord, int klantpasid)
{
Klantid = klantid;
Naam = naam;
Adres = adres;
Telefoonnummer = telefoonnummer;
Woonplaats = woonplaats;
Email = email;
Wachtwoord = wachtwoord;
Klantpasid = klantpasid;
}
}
}
Please provide me some help, tell me where i have to place the right code so i can continue my school project. The error i am getting now is ''' The specified conversion is invalid
'''
You can check klantid for DBNull.Value, and if it is, assign corresponding special int value; so instead of
(int)reader["klantid"]
put
reader.IsDBNull(reader.GetOrdinal("klantid")) ? -1 : Conver.ToInt32(reader["klantid"])
a better way is to declare private int klantid; as private int? klantid; (nullable int):
private int? klantid; // it can accept null now
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
then while reading from reader we can use turnary operator:
KlantId = !reader.IsDBNull(reader.GetOrdinal("klantid"))
? Conver.ToInt32(reader["klantid"])
: null;
I know a fix for you,
You change Klantpasid from int? to int
If klantpasid is null in your database, we set the value to 0 instead of null
public int Klantpasid
{
get
{
return klantpasid;
}
set
{
if( value == null){
klantpasid = 0;
}else {
klantpasid = value;
}
}
}
You can declare your property as nullable
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
Check out more on documentation.
When you read your data with a DataReader, it will return DBNull.Value. Whe you want to fill your Klant.Klantpasid value (which is of type Nullable<int>), you will have to convert the value to Nullable<int> yourself. When ADO.NET was first implemented, there were no nullable values, so they introduced DBNull instead. More modern approaches like Entity Framework use nullable types instead.
You can write a helper method to help converting your read value to a nullable type:
static T? AsNullable<T>(object value) where T : struct {
switch (value) {
case T converted:
return converted;
case DBNull:
return default(T?);
default:
throw new InvalidCastException();
}
}
So instead of...
(int)reader["klantpasid"]
...you write:
AsNullable<int>(reader["klantpasid"])
And of course you change the type of your constructor parameter from int to int?.
I am tring to motify a static property, I don't know where I am getting wrong. Here is the code.
public static string Id
{
get { return Id; }
set
{
if (Id.Length < Idlen)
{
var zero = new string('0', Idlen - Id.Length);
Id = zero + Id;
Id = value;
}
else
{
Id = Id.Substring(Id.Length - Idlen);
Id = value;
}
}
}
public static int Idlen { get; set; }
So here is an example of what I think you are trying to achieve. (Although ReSharper is telling me not to use these field names...)
private static string _Id;
public static string Id
{
get => _Id;
set // You want to use value here (new value), not Id (old value)
{
if (value == null)
{
// Consider what you want to do if user calls Id = null
_Id = new string('0', Idlen);
}
else if (value.Length < Idlen)
{
var zero = new string('0', Idlen - value.Length);
_Id = zero + value;
}
else
{
_Id = value.Substring(value.Length - Idlen);
}
}
}
public static int Idlen { get; set; }
I was using the "this" keyword in my default constructor, below is the code in the class movie
namespace Movie_List
{ enum GenreType { Action, War, Drama, Thriller };
class Movie
{
//Data Members
private String _title;
private int _rating;
private GenreType _type;
//Properties
public GenreType GenType
{
get { return _type; }
set { _type = value; }
}
public String Title
{
get { return _title; }
set { _title = value; }
}
public int Rating
{
get { return _rating; }
set { _rating = value; }
}
public Movie()
: this("Jaws", GenreType.Action, 4) { }
public Movie(String title, GenreType type, int rating ) //working ctor
{
Title = title;
GenType = type;
Rating = rating;
}
public override string ToString()
{
return String.Format(" {0} Genre : {1}, Rating: {2:d} Stars. ", Title, GenType, Rating);
}
}
I wanted to read in from a text file so i used this code in the MainWindow.xaml.cs
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
string lineIn = "";
string[] filmarray;
using (StreamReader file = new StreamReader("filmlist.txt"))
{
while ((lineIn = file.ReadLine()) != null)
{
filmarray = lineIn.Split(new char[] { ',' });
moviecollection.Add(new Movie()
{
Title = filmarray[0],
GenType = (GenreType)Enum.Parse(typeof(GenreType), filmarray[1]),
Rating = Convert.ToInt32(filmarray[2]),
});
lstFilms.ItemsSource = moviecollection;
}
}
}
I dont need this bit of code now
: this("Jaws", GenreType.Action, 4)
But when i deleted it, the genre action and rating 0 stars still prints.
Why is this Happening does anyone know?
When you have this initialization:
Movie movie = new Movie();
the empty constructor
public Movie() : this("Jaws", GenreType.Action, 4) { }
calls the overloaded constructor which have several parameters:
public Movie(String title, GenreType type, int rating) { ... }
When you delete this line: this("Jaws", GenreType.Action, 4) { }, what is happening now is that you are only calling the empty constructor which does nothing at all.
So when you call
int ratingValue = movie.Rating;
the default value of integer which is zero is returned because you did set anything on it.
UPDATE
a simple if (maybe, if I understand what you mean)
Assuming Rating should be greater than zero.
public override string ToString()
{
if (Rating == 0)
{
return String.Format("{0}", Title);
}
else
{
return String.Format(" {0} Genre : {1}, Rating: {2:d} Stars. ", Title, GenType, Rating);
}
}
It's because enum and int are always initialized with default value of 0.
It's not like string - if you don't initialize it will equal null. If you want to emulate this behavior for int, you can always try using int? type.
To get more details on this subject take a look at Default Values Table (C#).
My problem is that I have a List<> variable connected to another class, and I want to get all the items from that List<> and put it into a string.
In the result string, i'd like to see callNum, copyNum, content, author, year, title
Here is where I'm trying to put it into a string
public class CItemControl
{
//declare a list variable
private List<CItem> mItems;
private CItem mNewItem;
//a method that instantiates the list
public CItemControl()
{
mItems = new List<CItem>();
}
//attribute to get all items
public List<CItem> Items
{
get { return mItems; }
}
public CItem NewItem
{
get { return mNewItem; }
}
//method to add item to the CItem list
public void AddItem(int callNum, int copyNum, string content, string author, string year)
{
mNewItem = new CItem(callNum, copyNum, content, author, year);
mItems.Add(mNewItem);
}
//method to return all items to a string
public CItem ListAllItems()
{
string allItems;
}
Here is the class where I'm trying to get the items from. There will be variables added later.
class CItem
{
//declare attributes
private string mTitle;
private string mAuthor;
private string mContent;
private string mYear;
private int mCopyNum;
private int mCallNum;
private bool mHold = false;
private bool mBorrowed = false;
private bool mShelf = false;
//overload a constructor
public CItem(int CallNum, int CopyNum, string Content, string Author, string Year)
{
callNum = CallNum;
copyNum = CopyNum;
content = Content;
author = Author;
year = Year;
}
//create the default constructor
public CItem()
{
callNum = 0;
copyNum = 0;
content = "";
author = "";
year = "";
}
//set attributes
public int callNum
{
get { return mCallNum; }
set { mCallNum = value; }
}
public string content
{
get { return mContent; }
set { mContent = value; }
}
public string author
{
get { return mAuthor; }
set { mAuthor = value; }
}
public string year
{
get { return mYear; }
set { mYear = value; }
}
public string title
{
get { return mTitle; }
set { mTitle = value; }
}
public int copyNum
{
get { return mCopyNum; }
set { mCopyNum = value; }
}
public bool hold
{
get { return mHold; }
}
public bool borrowed
{
get { return mBorrowed; }
}
public bool shelf
{
get { return mShelf; }
}
//display information for users
public string displayInfo()
{
return "Call Number: " + callNum + ". Copy Number: " + copyNum + ". Title: " + title +
". Author: " + author + ". Year Published: " + year + ". Content: " + content;
}
//new method to display status of item
public string displayStatus()
{
if (borrowed == true)
return "Item is currently being borrowed.";
if (shelf == true && hold == false)
return "Item is available for borrowing.";
else
return "Item is on hold";
}
Any help is much appreciated!
Thanks in advance.
ListAllItems shall look something like this
public string ListAllItems()
{
var sb = new StringBuilder(); // var is of type StringBuilder
mItems.ForEach(item => sb.Append(item.displayInfo());
return sb.ToString();
}
return String.Join("; ", allItems.Select(item => item.displayInfo()));
You don't provide a lot of informations on how and what informations you want in your result string.
Can't you achieve this objective with a simple loop ?
using System.Text;
(...)
public string ListAllItems()
{
StringBuilder allItems = new StringBuilder();
foreach(CItem itm in Items){
allItems.AppendLine(itm.displayInfo());
}
return allItems.ToString();
}
Stringbuilder is optional but is faster than string concatenation.
I don't normally like to add formatter methods to property bags like this. If you want the flexibility to change have many formatting implementations, you might want to make a seperate class do the formatting.
public interface IFormatter<in T>
{
string Format(T obj);
}
public class CItemFormatter : IFormatter<CItem>
{
public string Format(CItem item)
{
//formatting logic
}
}