【发布时间】:2017-09-24 20:19:51
【问题描述】:
我有一个DataGridView 和一个DataTable 作为DataSource,一个Label 在DataGridView 中显示当前选定的单元格地址,最后有一个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