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

DataGridView自动更新数据
未处理 System.InvalidOperationException
  Message="操作无效,原因是它导致对 SetCurrentCellAddressCore 函数的可重入调用。"
  
//当点击按钮时调用 GetScore()方法,对 DataGridView 数据进行填充
 private void GetScore()
  {
  Scores score = new Scores();

  int iCourseId = Convert.ToInt32(lstCourse.SelectedItems[0].SubItems[1].Text);

  int iClassId = Convert.ToInt32(lstClass.SelectedItems[0].SubItems[1].Text);

  DataSet dsScore = score.SelectScore(-1, iCourseId, iClassId);


  this.dataGridView1.DataSource = dsScore;
  this.dataGridView1.DataMember = dsScore.Tables[0].TableName;
  }

//单击单元格时
  private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
  {
  if (this.dataGridView1.SelectedCells.Count == 1)//判断如果有选中的单元格
  {
   
  //得到选择的行
  int selectRowIndex = -1;
  try
  {
  selectRowIndex = this.dataGridView1.SelectedCells[0].RowIndex;
  }
  catch
  {
  }
  string score = this.dataGridView1.Rows[selectRowIndex].Cells[5].Value.ToString();
  string ScoreId = this.dataGridView1.Rows[selectRowIndex].Cells[4].Value.ToString();

  int iCourseId = Convert.ToInt32(lstCourse.SelectedItems[0].SubItems[1].Text);
  //
  if (score == "" && ScoreId == "")//如果分数列为空--插入
  {
  if (selectRowIndex != -1)
  {
  int stuId = -1;
  try
  {
  stuId = Convert.ToInt32(this.dataGridView1.Rows[selectRowIndex].Cells[0].Value);

  }
  catch
  {
  }

  if (stuId == -1)
  {
  return;
  }

  Scores s = new Scores();
  s.InsertScore(iCourseId, stuId, 0);//对分数表进行插入
  //如果随意的点几下,那么会插入很多相同的值 但是却无法立即显示在 DataGridView 里
  GetScore();
  //这里反回去重新填充新的数据就引发异常,但是自己点按钮却无异常发生....
  }
  }
  else
  {
  if (selectRowIndex != -1)
  {
  int scoreId = Convert.ToInt32(this.dataGridView1.Rows[selectRowIndex].Cells[4].Value);

  string obj = this.dataGridView1.Rows[selectRowIndex].Cells[5].Value.ToString();

  if (obj == "")
  {
  obj = "0";
  }

  float f = Convert.ToSingle(obj);
  int stuId = Convert.ToInt32(this.dataGridView1.Rows[selectRowIndex].Cells[0].Value);
  Scores s = new Scores();
  s.UpdateScore(scoreId, f);//更新分数

  }
  }