Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i m doing Crud operation using ADO.NET in visual studio 2015

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 14:         public string GetConnString()
Line 15:         {
Line 16:             string str = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;
Line 17: 
Line 18: 

Source File: F:\MVCASP.NET\ASPDotNETMVCClass\CurdOperation\Models\DataContext.cs    Line: 16 

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   CurdOperation.Models.DataContext.GetConnString() in F:\MVCASP.NET\ASPDotNETMVCClass\CurdOperation\Models\DataContext.cs:16
   CurdOperation.Models.DataContext.GetDepts() in F:\MVCASP.NET\ASPDotNETMVCClass\CurdOperation\Models\DataContext.cs:23
   CurdOperation.Controllers.HomeController.Index() in F:\MVCASP.NET\ASPDotNETMVCClass\CurdOperation\Controllers\HomeController.cs:15
   lambda_method(Closure , ControllerBase , Object[] ) +62
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9734909
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1532.0


What I have tried:

Step-1
i have taken one empty MVC application by naming As CRUDOperation...
then i have taken 2 classes in Model as Following..
1-Dept.cs
2-DataContext.cs
Detpt.cs i m using for property like as -Deptno,Dname,Loc,

Setp 2

i have created one Database naming As MyMvcdb..and inside this Database i have created one table name same as Model/class Dept and same coloum name.

step 3

In DataContext.cs Class i have written This Code as below...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


namespace CurdOperation.Models
{
    public class DataContext
    {
        public string GetConnString()
        {
            string str = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;


            return str;
        }
        public List<Dept> GetDepts()
        {
            string connStr = GetConnString();
            string cmdText = "SELECT * FROM DEPT";
            SqlDataAdapter da = new
           SqlDataAdapter(cmdText, connStr);
            DataSet ds = new DataSet();
            da.Fill(ds);
            List<Dept> deptList = new List<Dept>();
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                Dept obj = new Dept();
                obj.Deptno = (int)item[0];
                obj.Dname = (string)item[1];
                obj.Loc = (string)item[2];
                deptList.Add(obj);
            }
            return deptList;
        }

       

        public Dept GetDept(int dno)
        {
            string connStr = GetConnString();
            string cmdText = "SELECT * FROM Dept WHERE Deptno = " + dno;

            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(cmdText, conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            Dept obj = new Dept();
            if (dr.Read() == true)
            {
                obj.Deptno = (int)dr["Deptno"];
                obj.Dname = (string)dr["Dname"];
                obj.Loc = (string)dr["Loc"];
            }
            conn.Close();
            return obj;
        }
        public void ExecuteCommand(string cmdText)
        {
            string connStr = GetConnString();
            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(cmdText, conn);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        public void AddDept(Dept obj)
        {
            string str = string.Format("INSERT INTO Dept VALUES({0}, '{1}','{2}')", obj.Deptno, obj.Dname, obj.Loc);

            ExecuteCommand(str);
        }

        public void EditDept(Dept obj)
        {
            string str = string.Format("UPDATE Dept SET Dname = '{0}', Loc = '{1}' WHERE Deptno ={ 2} ", obj.Dname, obj.Loc, obj.Deptno);
            ExecuteCommand(str);
        }

        public void DeleteDept(int dno)
        {
            string str = "DELETE FROM Dept WHERE deptno = "+ dno;

            ExecuteCommand(str);
        }
    }
}
Posted
Updated 15-Nov-17 2:25am
Comments
Thanks7872 15-Nov-17 7:40am    
Make sure you have connection string as conn1 in your application.
Pankaj hyderabad 15-Nov-17 7:53am    
sir can you tell me process how to check Connection String
Karthik_Mahalingam 15-Nov-17 8:13am    
use  Reply   button to post comments/query to the concerned user, so that the user gets notified and respond to your text.
F-ES Sitecore 15-Nov-17 8:24am    
Google "Object reference not set to an instance of an object connectionstrings", this is asked every day.

Quote:
public string GetConnString()
Line 15: {
Line 16: string str = ConfigurationManager.ConnectionStrings["conn1"].Connectionstring"/>



You are getting this error because the ConnectionStrings node in the Web.Config doesnt contains the Key conn1 so obviously the below statement will return null
ConfigurationManager.ConnectionStrings["conn1"]; // null

So when you try to access the property (ConnectionString) of the above result which is null will throws the null reference exception.

Make sure that the config file contains the key conn1
<configuration>
  <connectionStrings>
    <add name="conn1" connectionString="Your Connectionstring"/>
  </connectionStrings>

refer this article to understand debugging in visual studio
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
 
Share this answer
 
v2
Comments
Pankaj hyderabad 15-Nov-17 12:41pm    
i have Configured web.config file As below
<configuration>
<connectionStrings>
<add name="conn1" connectionString="Your Connectionstring"/>
</connectionStrings>
Pankaj hyderabad 15-Nov-17 12:52pm    
thank you so much
Karthik_Mahalingam 15-Nov-17 20:48pm    
Welcome
This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out! Most likely, your web.config file does not contain a connection string called "conn1" - but we can't look to see!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900