【问题标题】:DataGridView with data source reports two different CurrentCellAddress row values带有数据源的 DataGridView 报告两个不同的 CurrentCellAddress 行值
【发布时间】:2017-09-24 20:19:51
【问题描述】:

我有一个DataGridView 和一个DataTable 作为DataSource,一个LabelDataGridView 中显示当前选定的单元格地址,最后有一个Button,该按钮打开一个@987654329 @ 显示当前选择的相同单元格地址。

标签的文本在 DataGridViews CellClick 事件中更新。

Using the picture below as an example: When the last “NewRow” is selected, the label will be updated correctly with the correct row five (5) index.但是,当我单击按钮并显示相同的选定单元格地址时,行索引为四 (4)。

我猜这与DataSource/DataTable 有关,因为如果DataGridView 未绑定到数据源,则不会发生这种情况。

我有一个解决方法,但是我不明白为什么相同的方法dataGridView1.CurrentCellAddress 似乎返回不正确/不同的值。从在单元格单击事件中调用方法CurrentCellAddress 以及稍后单击按钮时调用相同的方法时发生了什么?选择没有改变,但看起来它们是不同的数字。感谢您的帮助。

我用来测试的代码……

DataTable gridData;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  //FillGrid();
  gridData = GetTable();
  FillDT(gridData);
  dataGridView1.DataSource = gridData;
  label1.Text = "CurrentCellAddress: " + dataGridView1.CurrentCellAddress.ToString();
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Col1", typeof(String));
  dt.Columns.Add("Col2", typeof(String));
  dt.Columns.Add("Col3", typeof(String));
  return dt;
}

private void FillDT(DataTable dt) {
  for (int i = 0; i < 5; i++) {
    dt.Rows.Add("R" + i + "C1", "R" + i + "C2", "R" + i + "C3");
  }
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
  label1.Text = "CurrentCellAddress: " + dataGridView1.CurrentCellAddress.ToString();
}

private void btnGetCellAddress_Click(object sender, EventArgs e) {
  MessageBox.Show("CurrentCellAddress: " + dataGridView1.CurrentCellAddress.ToString(),"Cell Address");
}

// Method to fill the grid to show the values are correct 
// when the datagridview is not data bound
private void FillGrid() {
  dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
  dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
  dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
  for (int i = 0; i < 5; i++) {
    dataGridView1.Rows.Add("R" + i + "C1", "R" + i + "C2", "R" + i + "C3");
  }
}

【问题讨论】:

  • 这个不清楚,因为我很困惑。听起来很熟悉?

标签: c# datagridview datatable


【解决方案1】:

DataGridView控件失去焦点时,最终会调用OnValidating方法(source reference),其中包含以下代码:

// Current cell needs to be moved to the row just above the 'new row' if possible.
int rowIndex = this.Rows.GetPreviousRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible);

DataGridView 中选择单元格将焦点保持在控件上,因此永远不会调用它。但是,当使用按钮时,焦点会丢失,OnValidating 会将当前单元格移动到空的新行上方的一行。

【讨论】:

  • 你是对的。答案中的链接还解释了为什么如果没有数据源,值会正确返回。您链接到的 OnRowValidated 参考中的大型 if 语句中的第一个条件是 if (this.DataSource != null &amp;&amp;..... 这显然可以解释正在发生的事情。感谢您的深刻解释。
猜你喜欢
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2021-03-30
相关资源
最近更新 更多