(菜鸟求解)
未将对象引用设置到对象的实例static DataSet ds;
static SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindInfo();
tianjia.Visible = false;
if (Request["a"] == "update")
{
tianjia.Visible = true;
int id = Convert.ToInt32(Request["id"]);
DataRow dr = ds.Tables["Users"].Rows.Find(id);
txtName.Value=dr[1].ToString();
txtPwd.Value=dr[2].ToString();
}
}
}
protected void BindInfo()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
da = new SqlDataAdapter("select * from Users", conn);
ds = new DataSet();
da.Fill(ds,"Users");
ds.Tables["Users"].Columns[0].AutoIncrement = true;
ds.Tables["Users"].Columns[0].AutoIncrementSeed = 1;
ds.Tables["Users"].Columns[0].AutoIncrementStep = 1;
ds.Tables["Users"].PrimaryKey = new DataColumn[] { ds.Tables["Users"].Columns["id"] };//给表设置主键
gvData3.DataSource = ds;
gvData3.DataBind();
}
protected void btinti_chlick(object sender, EventArgs e)
{
tianjia.Visible = false;
if (Request["a"] == "updata")
{
int id = Convert.ToInt32(Request["id"]);
DataRow dr = ds.Tables[0].Rows.Find(id);
dr[1] = txtName.Value;
dr[2] = txtPwd.Value;
}
else
{
DataRow dr = ds.Tables["Users"].NewRow(); //报错就是这句
dr["name"] = txtName.Value;
dr["pwd"] = txtPwd.Value;
ds.Tables["Users"].Rows.Add(dr);
}
BindInfo();
txtName.Value = "";
txtPwd.Value = "";
}
我做的是给表添加数据的按钮事件 结果就报错了 如题 真心不知道 我都快和老师的代码打的一模一样了
------解决方案--------------------DataSet ds 你看下这个值是不是null
------解决方案--------------------
判断一下
if(ds.Tables[0].Rows.Count>0)
{
DataRow dr = ds.Tables["Users"].NewRow(); //报错就是这句
dr["name"] = txtName.Value;
dr["pwd"] = txtPwd.Value;
ds.Tables["Users"].Rows.Add(dr);
}
------解决方案--------------------像楼上那样判断一下试试先,应该是可以的吧