以下是小弟的代码:
private void SavCour_Click(object sender, EventArgs e)
{
try
{
int n = DataGirdview1.CurrentRow.Index;
this.DataGirdview1.CurrentCell = DataGirdview1[0, n];
if (DS.HasChanges())
{
this.AddCourConn = new SqlConnection(this.AddCourConnStr);
this.AddCourDA = new SqlDataAdapter(this.AddCourSql, this.AddCourConn);
AddCourComm = new SqlCommandBuilder(AddCourDA);
this.AddCourDA.Update(this.DS.GetChanges(), "Course");
MessageBox.Show("保存成功", "信息");
}
}
catch(Exception Eq)
{
MessageBox.Show(Eq.ToString(),"信息");
}
}
private void DelCour_Click(object sender, EventArgs e)
{ int rowNumber = DataGirdview1.CurrentRow.Index; try
{
this.DS.Tables[0].Rows[rowNumber].Delete();
this.AddCourConn = new SqlConnection(this.AddCourConnStr);
AddCourDA = new SqlDataAdapter("", AddCourConn);
AddCourComm = new SqlCommandBuilder(AddCourDA);
AddCourDA.Update(this.DS.GetChanges(), "Course");
MessageBox.Show("删除成功", "信息");
}
catch
{}
}
程序可以运行,而且删除也能成功,删除几条信息后的结果也能保存在数据库里,但是如果把所有记录删除再保存的话就失败了。我用try catch捕获到“未将对象引用设置到对象的实例”~请问大侠们知道原因吗?应该怎么改?跪求您的回复了..
private void SavCour_Click(object sender, EventArgs e)
{
try
{
int n = DataGirdview1.CurrentRow.Index;
this.DataGirdview1.CurrentCell = DataGirdview1[0, n];
if (DS.HasChanges())
{
this.AddCourConn = new SqlConnection(this.AddCourConnStr);
this.AddCourDA = new SqlDataAdapter(this.AddCourSql, this.AddCourConn);
AddCourComm = new SqlCommandBuilder(AddCourDA);
this.AddCourDA.Update(this.DS.GetChanges(), "Course");
MessageBox.Show("保存成功", "信息");
}
}
catch(Exception Eq)
{
MessageBox.Show(Eq.ToString(),"信息");
}
}
private void DelCour_Click(object sender, EventArgs e)
{ int rowNumber = DataGirdview1.CurrentRow.Index; try
{
this.DS.Tables[0].Rows[rowNumber].Delete();
this.AddCourConn = new SqlConnection(this.AddCourConnStr);
AddCourDA = new SqlDataAdapter("", AddCourConn);
AddCourComm = new SqlCommandBuilder(AddCourDA);
AddCourDA.Update(this.DS.GetChanges(), "Course");
MessageBox.Show("删除成功", "信息");
}
catch
{}
}
程序可以运行,而且删除也能成功,删除几条信息后的结果也能保存在数据库里,但是如果把所有记录删除再保存的话就失败了。我用try catch捕获到“未将对象引用设置到对象的实例”~请问大侠们知道原因吗?应该怎么改?跪求您的回复了..
this.DataGirdview1.CurrentCell = DataGirdview1[0, n];
这句话,全部数据删除后DataGirdview1里面就没数据,也没DataGirdview1.CurrentRow为null了,再取它的索引的话当然会出问题的,你可以断点放在这句上看看
把Try,Catch去掉,看看出什么错误先。
在n后面加上一条if(n>=0)或者if(n!=-1)的语句试试看。
int n = DataGirdview1.CurrentRow.Index;
this.DataGirdview1.CurrentCell = DataGirdview1[0, n];
你加: if(this.DataGirdview1.CurrentCell !=null)
{
int n = DataGirdview1.CurrentRow.Index;
this.DataGirdview1.CurrentCell = DataGirdview1[0, n];
}