对象引用未设置对象的实例 [英] object reference not set an instance of an object

查看:73
本文介绍了对象引用未设置对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"/ODSeg1"应用程序中的服务器错误.
对象引用未设置为对象的实例.
说明:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪,以获取有关错误及其在代码中起源的详细信息.

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例.

源错误:

Server Error in ''/ODSeg1'' 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 22:  List<Product> products = new List<Product>();
Line 23:         string cs = "Data Source=SERVER\\SERVERDB;Initial Catalog=lp;User ID=sa;Password=Pentag0n";
Line 24:         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[cs].ConnectionString);
Line 25:         SqlCommand cmd = new SqlCommand("select * from Products", con);
Line 26:         con.Open();

推荐答案

阅读有关如何使用的信息ConfigurationManager:

http://social.msdn.microsoft.com/Forums/zh/csharpgeneral/thread/b3ae17b1-5b32-4079-997e-0b704988aca7 [
Read this on how to use the ConfigurationManager :

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/b3ae17b1-5b32-4079-997e-0b704988aca7[^]


尝试调试断点并查找产生错误的行
使用像
try to debug through break point and find line that generates errors
use like
string cs = "Data Source=SERVER\\SERVERDB;Initial Catalog=lp;User ID=sa;Password=Pentag0n";
       SqlConnection con = new SqlConnection();
        con.ConnectionString=cs;
       con.Open();
        SqlCommand cmd = new SqlCommand("select * from Products", con);


实际上,您在配置文件中使用了错误的"KEY"作为连接字符串.

Actually, You have used wrong "KEY" for connections string in Config file.

List<product> products = new List<product>();
string cs = "Data Source=SERVER\\SERVERDB;Initial Catalog=lp;User ID=sa;Password=Pentag0n";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[cs].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from Products", con);
con.Open();</product></product>



在这里,您已将"cs"用作KEY.而不是直接将其用作连接字符串.像这样..



here you have used "cs" as KEY. rather use it as directly as connection string. like this..

SqlConnection con = new SqlConnection(cs);



或像这样更改配置文件.



or change in config file like this..

<connectionstring>
   <add key="cs" value="Data Source=SERVER\\SERVERDB;Initial Catalog=lp;User ID=sa;Password=Pentag0n">
</add></connectionstring>



然后像这样使用..



then use like this..

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[cs].ConnectionString);



希望它能工作..



hope it works..


这篇关于对象引用未设置对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆