【发布时间】:2010-06-15 16:50:16
【问题描述】:
双击该行后,我需要 C# 中的 sn-p 代码来维护从 DataGridView 中选择的行。
现在我正在显示来自数据集的数据,选择模式是FullRowSelect。
有什么方法可以设置吗?
有两种情况需要处理:
- 每次计时器计时所选行时,总是转到 datagridview 的第一行。
- 单击一行后,它会被选中,但在计时器计时后,所选行会转到第一行。
感谢您的帮助!
新手程序员
【问题讨论】:
双击该行后,我需要 C# 中的 sn-p 代码来维护从 DataGridView 中选择的行。
现在我正在显示来自数据集的数据,选择模式是FullRowSelect。
有什么方法可以设置吗?
有两种情况需要处理:
感谢您的帮助!
新手程序员
【问题讨论】:
你必须在函数timer_tick中做到这一点
private void timer3_Tick(object sender, EventArgs e)
{
int rowIndex;
if (dgvOrdini.Rows.Count == 0) //here I check if the dgv is empty
rowIndex = 0;
else
// I save the index of the current row in rowIndex
rowIndex = this.dgvOrdini.CurrentCell.RowIndex;
.......
.......
if (dgvOrdini.Rows.Count != 0) //Now if the dgv is not empty
//I set my rowIndex
dgvOrdini.CurrentCell = dgvOrdini.Rows[rowIndex].Cells[0];
}
使用此方法,所选行不会改变。
【讨论】:
试试这个。 先保存实际选中行的索引
int index = -1 //set the index to negative (because if you have only 1 row in your grid, this is a zero index
if (yourdatagridview.Rows.Count > 0) //if you have rows in datagrid
{
index = yourdatagridview.SelectedRows[0].Index; //then save index into variable
}
现在您可以更新 datagridview...
更新后你必须设置选中的行:
if (index != -1) //if index == -1 then you don't have rows in your datagrid
{
yourdatagridview.Rows[index].Selected = true;
}
它的作品!
【讨论】:
现在我正在显示数据集中的数据,选择模式是
FullRowSelect。有什么方法可以设置吗?
DataGridView.SelectionMode 属性将通过 DataGridViewSelectionMode 枚举为您执行此操作。
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
至于你的其他问题,我认为需要进一步的细节。你追求什么样的行为?
编辑#1
根据您的评论:
在我连续单击后,会打开一个新表单。问题是每次启用计时器时都会调用 populate_DatagridView 方法,并且选定的行位于第一行,而不是保持选中的行被点击。
一种解决方案可能如下:
private _dataGridViewRowSelectedIndex;
private void dataGridview1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
DataGridView dgv = (DataGridview)sender;
if (dgv.Rows.GetRowState(e.RowIndex) == DataGridViewElementStates.Selected)
_dataGridViewRowSelectedIndex = e.RowIndex;
// Open your form here...
// And when your form returns...
// Set the selected index like so
dgv.Rows[_dataGridViewRowSelectedIndex].Selected = true;
}
这对您有帮助吗?
【讨论】: