static void Main(string[] args)
{
  SqlConnection con=new SqlConnection();
  SqlCommand com=new SqlCommand();
  SqlDataAdapter sa=new SqlDataAdapter();
  DataSet ds=new DataSet();  con.ConnectionString="server=SOHO;database=DataAn;uid=sa";
  con.Open();
  com.CommandText="select * from tabelTest";
  com.Connection=con;  sa.SelectCommand=com;
  sa.Fill(ds,"tabelTest");
  foreach(DataRow thisRow in ds.Tables["tabelTest"].Rows)
 {
Console.WriteLine(thisRow["name"]);
  }  DataRow newRow=ds.Tables["tabelTest"].NewRow();
  newRow["id"]="3";
  newRow["name"]="wangzhanli";
  ds.Tables["tabelTest"].Rows.Add(newRow);
  Console.WriteLine("this row is state {0}",newRow.RowState);
 
  Console.WriteLine("after update");
  ds.AcceptChanges();
  foreach(DataRow thisRow in ds.Tables["tabelTest"].Rows)
  {
Console.WriteLine(thisRow["name"]);
  }
  DataSet newDs;
  newDs=ds.GetChanges(DataRowState.Added);
  foreach(DataRow thisRow in newDs.Tables["tabelTest"].Rows)
  {
  Console.WriteLine(thisRow["name"]);
  }
}我执行到foreach(DataRow thisRow in newDs.Tables["tabelTest"].Rows)这句时报空指针的错误,请大虾们指教
并且提示DataRowState.Added超出范围,不明白

解决方案 »

  1.   

    删除语句: ds.AcceptChanges(); (或者把它放到程序的最后)试试
      

  2.   

    楼主小妹对DataSet的AcceptChanges()方法不甚了解。
    msdn上对AcceptChanges()方法的解释是:
    当对DataSet调用AcceptChanges时,任何仍处于编辑模式的DataRow对象都将成功结束编辑。每个DataRow的RowState属性也会随之更改;状态为Added和Modified的行的状态将变为Unchanged,状态为Deleted的行则被移除。你在这一行 newDs=ds.GetChanges(DataRowState.Added); 使用 DataRowState 枚举定义的行状态值当作参数进行传递,那么返回的是你所添加的行。所以后面的foreach语句当然会出错。
    调用AcceptChanges方法之后,所有行都设置为未更改,GetChanges方法所需的信息也不再存在。
    如果你需要处理更改的行,必须在调用AcceptChanges()方法之前调用GetChanges()。
    所以你可以将ds.AcceptChanges(); 放到本方法的最后一条语句。
      

  3.   

    .....
    ds.AcceptChanges(); //表示已经提交了
    .....
    newDs=ds.GetChanges(DataRowState.Added);  //提取状态为Added的.当然提不到了
    .....修改方法:   去掉ds.AcceptChanges(); 这句