system.null引用异常 [英] system.null reference exception
问题描述
我在行中收到以下错误
con = new SqlConnection(ConfigurationManager.ConnectionStrings [Connect]。ToString());下面的代码...
错误:
system.nullreferenceexception对象引用未设置为对象的实例。
i m getting the following error in the line
"con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());" of code below...
Error:
"system.nullreferenceexception object reference not set to an instance of an object."
public partial class _Default : System.Web.UI.Page
{
SqlDataAdapter da;
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
public void BindData()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());//getting error in this line
cmd = new SqlCommand("Select * from b_asset_master", con);
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
Grid.DataSource = ds;
Grid.DataBind();
con.Close();
}
protected void Grid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
Grid.CurrentPageIndex = e.NewPageIndex;
BindData();
}
}
推荐答案
con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());//getting error in this line
你正在使用的这行
in this line you are using
ConfigurationManager.ConnectionStrings["Connect"].ToString()
但我认为配置文件中不存在连接键。或者你在那里使用了错误的法术。
but i think "Connect" key dose not exist in your config file. or you using wrong spell there.
它取决于它在哪一行,但最明显的候选者是:
It depends which line it is on, really, but the most obvious candidate is:
cmd.CommandText = "Select * from b_asset_master";
如果您没有为cmd分配值,那么您将收到此错误。
尝试将其更改为:
If you have not assigned a value to cmd, then you will get this error.
Try changing it to:
cmd = new SqlCommand("Select * from b_asset_master", con);
并丢弃后面的行。问题应该消失。
当你遇到这样的问题时,首先要做的是查看调试器中的代码,找到变量 null
- 您通常可以很容易地从您需要做的事情中解决。它比很多,比每次问这里快得多! :笑:
and discard the line after it. The problem should go away.
When you get a problem like this, the first thing to do is look at the code in the debugger, and find the variable that is null
- you can usually work out pretty easily from that what you need to do. And it's a lot, lot quicker than asking here each time! :laugh:
ds
来自哪里?看起来是null
。
Where does thatds
come from? Looks like that isnull
.
这篇关于system.null引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!