0

Hy Master, I try to create CRUD in MVS ASP.net, but I have one problem when I build and RUN my program This my model, EmployeeDB :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace CRUDAjax.Models
{
    public class EmployeeDB
    {
        //declare connection string
        string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

        //Return list of all Employees
        public List<Employee> ListAll()
        {
            List<Employee> lst = new List<Employee>();
            using(SqlConnection con=new SqlConnection(cs))
            {
                con.Open();
                SqlCommand com = new SqlCommand("SelectEmployee",con);
                com.CommandType = CommandType.StoredProcedure;
                SqlDataReader rdr = com.ExecuteReader();
                while(rdr.Read())
                {
                    lst.Add(new Employee { 
                        EmployeeID=Convert.ToInt32(rdr["EmployeeId"]),
                        Name=rdr["Name"].ToString(),
                        Age = Convert.ToInt32(rdr["Age"]),
                        State = rdr["State"].ToString(),
                        Country = rdr["Country"].ToString(),
                    });
                }
                return lst;
            }
        }

        //Method for Adding an Employee
        public int Add(Employee emp)
        {
            int i;
            using(SqlConnection con=new SqlConnection(cs))
            {
                con.Open();
                SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@Id",emp.EmployeeID);
                com.Parameters.AddWithValue("@Name", emp.Name);
                com.Parameters.AddWithValue("@Age", emp.Age);
                com.Parameters.AddWithValue("@State", emp.State);
                com.Parameters.AddWithValue("@Country", emp.Country);
                com.Parameters.AddWithValue("@Action", "Insert");
                i = com.ExecuteNonQuery();
            }
            return i;
        }

        //Method for Updating Employee record
        public int Update(Employee emp)
        {
            int i;
            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();
                SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@Id", emp.EmployeeID);
                com.Parameters.AddWithValue("@Name", emp.Name);
                com.Parameters.AddWithValue("@Age", emp.Age);
                com.Parameters.AddWithValue("@State", emp.State);
                com.Parameters.AddWithValue("@Country", emp.Country);
                com.Parameters.AddWithValue("@Action", "Update");
                i = com.ExecuteNonQuery();
            }
            return i;
        }

        //Method for Deleting an Employee
        public int Delete(int ID)
        {
            int i;
            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();
                SqlCommand com = new SqlCommand("DeleteEmployee", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@Id", ID);
                i = com.ExecuteNonQuery();
            }
            return i;
        }
    }
}

And this my controler HomeController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRUDAjax.Models;

namespace CRUDAjax.Controllers
{
    public class HomeController : Controller
    {
        EmployeeDB empDB = new EmployeeDB();
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult List()
        {
            return Json(empDB.ListAll(),JsonRequestBehavior.AllowGet);
        }
        public JsonResult Add(Employee emp)
        {
            return Json(empDB.Add(emp), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetbyID(int ID)
        {
            var Employee = empDB.ListAll().Find(x => x.EmployeeID.Equals(ID));
            return Json(Employee, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Update(Employee emp)
        {
            return Json(empDB.Update(emp), JsonRequestBehavior.AllowGet);
        }
        public JsonResult Delete(int ID)
        {
            return Json(empDB.Delete(ID), JsonRequestBehavior.AllowGet);
        }
    }
}

This the erorr output

System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=CRUDAjax
  StackTrace:
       at CRUDAjax.Models.EmployeeDB..ctor() in c:\users\jujur\documents\visual studio 2015\Projects\CRUDAjax\CRUDAjax\Models\EmployeeDB.cs:line 15
       at CRUDAjax.Controllers.HomeController..ctor() in c:\users\jujur\documents\visual studio 2015\Projects\CRUDAjax\CRUDAjax\Controllers\HomeController.cs:line 12
  InnerException

: ScreenShot Erorr

  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Tetsuya Yamamoto May 24 '17 at 03:54
  • You should debug your application and check your ConnectionStrings settings. – Jeroen Heier May 24 '17 at 03:57
  • 1
    As the exception states, something on line 15 in ``EmployeeDB.cs`` is null. It is probably the variable ``cs``, likely caused by the configuration manager not being able to find a connection string with the name "DBCS". – J.N. May 24 '17 at 03:58
  • @JeroenHeier how to check your ConnectionStrings settings? – Jujur Sitanggang May 24 '17 at 03:58
  • You should read the [documentation](https://msdn.microsoft.com/en-us/library/ms178411.aspx). – Jeroen Heier May 24 '17 at 04:03
  • @J.N. i try this CRUD from tutorial, how i to fix connection string with the name "DBCS"? – Jujur Sitanggang May 24 '17 at 04:03
  • @JujurSitanggang Go to web.config check your connection string with the "Key" named = "DBCS". – Drew Aguirre May 24 '17 at 04:08
  • The ``ConfigurationManager`` reads the configuration stored in your .config file of your project. Do you see any connection strings in a file ending with .config? – J.N. May 24 '17 at 04:08
  • is it okay if you can add your web.config or app.config code ? – Drew Aguirre May 24 '17 at 04:12
  • @J.N. i dont know what you mind, actually i newbie in ASP hehe – Jujur Sitanggang May 24 '17 at 04:12
  • @JujurSitanggang - Somewhere in your project, you should have a file with the extension .config -- these are usually called something like ``web.config`` or ``app.config``. Do you have one of those? – J.N. May 24 '17 at 04:14
  • @J.N. i have web.config – Jujur Sitanggang May 24 '17 at 04:16
  • Do you see a connection strings section in that file? Looks something like this: `` `` – J.N. May 24 '17 at 04:17
  • @J.N. no i dont see a ` ` in my web.config – Jujur Sitanggang May 24 '17 at 04:20
  • My question was if there is anything that **looks** like a connection strings section. I think that you will have more luck following a tutorial like this: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string , than short comments on StackOverflow. – J.N. May 24 '17 at 04:27

2 Answers2

0

better check if there is null value before converting to integer or decimal,otherwise check NULL value in database ISNULL(@Variable,0)...the choice is yours

rohit poudel
  • 43
  • 1
  • 8
  • this my database, `CREATE TABLE [dbo].[Employee] ( [EmployeeID] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (50) NULL, [Age] INT NULL, [State] NVARCHAR (50) NULL, [Country] NVARCHAR (50) NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([EmployeeID] ASC) );` i think its not converting to integer or decimal – Jujur Sitanggang May 24 '17 at 06:36
  • Here Age might be null so you have two choices 1.C# Code check if value is null or not before converting to Integer 2. SQL ISNULL(Age,0) on the query 3 Convert.ToString is Safer than .ToString because .ToString does not handle the null sometimes – rohit poudel May 24 '17 at 07:26
0

the connection string hasn't been found, please double check that the connection string exists.

string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;