读书人

小弟我用DataSet更新到数据库中出错了

发布时间: 2013-04-05 10:24:33 作者: rapoo

我用DataSet更新到数据库中出错了,求大神帮忙休息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class DataUpdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

string str="server='(local)';database='mydatabase';uid='sa';pwd='666666'";
SqlConnection con = new SqlConnection(str);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from hlmobile",con);
SqlCommandBuilder build = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds,"hlmobile");
DataTable tb = new DataTable("hlmobile");
tb.PrimaryKey = new DataColumn[] {
tb.Columns["id"]
};
DataRow row = ds.Tables["hlmobile"].NewRow();
row["hltype"] = "美女";
row["id"] = 23;
ds.Tables["hlmoblie"].Rows.Add(row); da.Update(ds, "hlmobile");

}
}







错误信息----------------
“/DataPractise”应用程序中的服务器错误。
未将对象引用设置到对象的实例。
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

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

源错误:


行 24: tb.Columns["id"]
行 25: };
行 26: DataRow row = ds.Tables["mobile"].NewRow();
行 27: row["hltype"] = "美女";
行 28: row["id"] = 23;


源文件: f:\WebProject\Web\DataPractise\DataUpdate.aspx.cs 行: 26

堆栈跟踪:


[NullReferenceException: 未将对象引用设置到对象的实例。]
DataUpdate.Page_Load(Object sender, EventArgs e) in f:\WebProject\Web\DataPractise\DataUpdate.aspx.cs:26
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
求大神帮忙解决
------解决方案--------------------


DataTable tb = new DataTable("hlmobile");
这是多余的,
da.Fill(ds,"hlmobile");已经在ds数据库中实例了一个叫做hlmobile的表
DataTable tb=ds["hlmobile"];或者直接使用ds["hlmobile"]

读书人网 >asp.net

热点推荐