日期:2014-05-18  浏览次数:20973 次

wpf填充datagridview方法
public void ListTeacher()
  {
  this.datagridview2.AllowUserToAddRows = false;
  DataSet ds = new DataSet();
  string sql = string.Format("select tname from teacher");
  SqlDataAdapter adapter = new SqlDataAdapter(sql,DBHelper.connection);
  DBHelper.connection.Open();
  adapter.Fill(ds,"Teacher");
  datagridview2.DataSource = ds.Tables[0];
  DBHelper.connection.Close();
  }

这个方法总是报出“未将对象引用到对象的实例

------解决方案--------------------
怎么不是应该先打开Connection么?
出错应该是
datagridview2.DataSource = ds.Tables[0];
ds.Tables[0]有内容么?

public void ListTeacher()
{
this.datagridview2.AllowUserToAddRows = false;
DataSet ds = new DataSet();
DBHelper.connection.Open(); // 这一句提前吧
string sql = string.Format("select tname from teacher");
SqlDataAdapter adapter = new SqlDataAdapter(sql,DBHelper.connection);
adapter.Fill(ds,"Teacher");
datagridview2.DataSource = ds.Tables[0];
DBHelper.connection.Close();
}