我如何选择DataGridView中的最后一行 [英] how can i select the last row in DataGridView

查看:158
本文介绍了我如何选择DataGridView中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次加载表单时,我需要在DataGridView中选择最后一行.所以我在Form_Load事件中编写了这段代码:

I need to select the last row in DataGridView, when form loads the first time. So I wrote this code in Form_Load event :

da.SelectCommand = new SqlCommand("SELECT * FROM Days", cn);

ds.Clear();
da.Fill(ds);

dataGridView1.DataSource = dsD.Tables[0];
dataGridView1.ClearSelection();
int nRowIndex = dataGridView1.Rows.Count - 1;
dataGridView1.Rows[nRowIndex].Selected = true;
dataGridView1.FirstDisplayedScrollingRowIndex = nRowIndex;
dataGridView1.Refresh();



但是,这没有做任何事情.它仍然选择第一行,但是当我将数据保存在数据库中然后填充数据集时,此代码有效.但是为什么不第一次加载表单呢?



But this isn´t doing anything. It still selects the first row, but this code works when I save the data in the database and then fill the dataset. But why not the first time when I load the form.

推荐答案

是的,此控件和文档的整个设计有点误导.尝试改为设置CurrentCell:

Yes, the whole design of this control and documentation is a bit misleading. Try to set CurrentCell instead:

dataGridView1.CurrentCell = dataGridView1.Rows[nRowIndex].Cells[0];



即使您使用选择模式选择整个行,也会在选择时获得理想的效果.您面临的问题是由于在所有情况下都将单元格视为真正的选择对象,而不是一行.对我来说,看起来有些API不一致.无论如何,尝试一下.

顺便说一句,不要使用dataGridView1之类的名称,这违反了Microsoft的命名约定.是的,该名称是由Microsoft Designer创建的,但是谁说您可以保留此名称?所有成员都应在语义上重命名;重新分解引擎是您的朋友.

—SA



It will give you desired effect on selection, even if you use the selection mode to select entire row. The problem you faced was due to the fact that the cell is considered to be a real object of selection in all cases, not a row. To me, it looks like some API inconsistency. Anyway, try it.

By the way, don''t use the names like dataGridView1, this is violation of Microsoft naming conventions. Yes, the name is created by Microsoft Designer, but who said you can keep this names? All members should be renamed semantically; re-factorization engine is your friend.

—SA


这篇关于我如何选择DataGridView中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆