【问题标题】:{"Object reference not set to an instance of an object."}{“你调用的对象是空的。”}
【发布时间】:2013-07-22 23:42:09
【问题描述】:

使用 C# 创建一个 ASP.NET 表单,我遇到了这个错误,我不知道它的错误是什么。一切都很好,但是当我按下保存按钮时,它给了我这个错误:

     NulllRefrenceException was unhandled by user code
    {"Object reference not set to an instance of an object."}
Object reference not set to an instance of an object.

代码:

     protected void Button8_Click(object sender, EventArgs e)
    {
         SqlConnection cnn = new SqlConnection();
         cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlAddSave"].ConnectionString;
    cnn.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "select * from  DisplayPP";
    cmd.Connection = cnn;
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds, " DisplayPP ");
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    DataRow drow = ds.Tables["DisplayPP"].NewRow();
    drow["website"] = web.Text;
    drow["country"] = DropDownList1.SelectedItem.Text;
    drow["contact"] = TextBox144.Text;
    drow["cat"] = TextBox145.Text;
    drow["traff"] = TextBox146.Text;

    more text boxes as above

    ds.Tables["DisplayPP "].Rows.Add(drow);
    da.Update(ds, " DisplayPP ");
    string script = @"<script language=""javascript"">
    alert('Information have been Saved Successfully.......!!!!!.');
   </script>;";
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
    }

请帮忙。

连接字符串:

<add name="sqlAddSave" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\PPTableDisplay.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />

异常

异常详情:System.NullReferenceException 未被用户处理 code HResult=-2147467261 Message=对象引用未设置为 对象的实例。来源=TestCRole StackTrace:在 TestCRole._Default.Button8_Click(Object sender, EventArgs e) in c:\Users\xxxxx\Documents\Visual Studio 2012\Projects\WindowsAzure2\TestCRole\Default.aspx.cs:第 60 行 System.Web.UI.WebControls.Button.RaisePostBackEvent(字符串 eventArgument) 在 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,布尔型 includeStagesAfterAsyncPoint) 内部异常:

【问题讨论】:

  • 在哪里你得到错误?
  • 使用调试器找出什么是空的。
  • TextBox146.Text 你应该为你的控件命名。
  • 请在第一行下一个断点并逐步调试(使用F10)。这样你就可以确定哪个对象没有被设置。
  • @Slaks 你的意思是 TextBox146.Text 应该命名你的控件???

标签: asp.net sql nullreferenceexception


【解决方案1】:
ds.Tables["DisplayPP "].Rows.Add(drow);

应该是这样的

ds.Tables["DisplayPP"].Rows.Add(drow);

【讨论】:

  • 他在这一行之前抛出了异常。
  • @Dimitar Dimitrov 他是对的,我遇到了同样的错误。
  • @JohnKim 哦,好吧,你在 cmets 中说的不一样 :) 没关系
  • 谢谢伙计!我修复了这个问题,因为之前在 sqlconneciton 字符串中创建错误是一样的。我还必须添加 ID 吗??我呢??表示 ID 是自动生成的,所以我将其保留原样.. 并得到了那个错误:无法将值 NULL 插入列 'Id',表 'C:\USERS\XXXXXXX\DOCUMENTS\VISUAL STUDIO 2012\PROJECTS\WINDOWSAZURE2\TESTCROLE \APP_DATA\PPTABLEDISPLAY.MDF.dbo.DisplayPP';列不允许空值。插入失败。
  • 您的 Id 列是否应该是一个身份,但您没有将其设置为这样?如果不设置identity属性,添加记录时不会自动填充字段,会出现这个错误
猜你喜欢
  • 2013-05-27
  • 1970-01-01
相关资源
最近更新 更多