DataGridView使用技巧一:获取或设置当前单元格的内容

当前单元格指的是DataGridView焦点所在的单元格,它可以通过DataGridView对象的CurrentCell属性取得。如果当前单元格不存在的时候,返回null。

取得当前单元格的内容:

object obj = this.dgv_PropDemo.CurrentCell.Value;

注:返回值是object类型的。

取得当前单元格的列Index:

int columnIndex = this.dgv_PropDemo.CurrentCell.ColumnIndex;

取得当前单元格所在的行的Index:

int rowIndex= this.dgv_PropDemo.CurrentCell.RowIndex;

另外,使用DataGridView.CurrentCellAddress属性来确定单元格所在的行:

int row= this.dgv_PropDemo.CurrentCellAddress.Y;

列:

int column = this.dgv_PropDemo.CurrentCellAddress.X;

注:DataGridView的行和列的索引都是从0开始的。

当前的单元格可以通过设定DataGridView对象的CurrentCell来改变。

DataGridView1.CurrentCell=DataGridView1[int columnIndex,int rowIndex];

注:如果DataGridVIew的选中模式是行选择,那么会选中当前单元格所在的整行。否则只会选中设置的当前单元格。

将CurrentCell设置为Null可以取消激活的当前单元格。

示例:设置第一行第二列为当前的CurrentCell

this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[1, 0];

示例:通过向上和向下实现遍历DataGridView

复制代码
 1 /// <summary>
 2         /// 向上遍历
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btn_Up_Click(object sender, EventArgs e)
 7         {
 8             //获取上一行的索引
 9             int upRowIndex = this.dgv_PropDemo.CurrentCell.RowIndex - 1;
10             if (upRowIndex < 0)
11             {
12                 //选中最后一行
13                 this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, this.dgv_PropDemo.RowCount - 1];
14             }
15             else
16             {
17                 this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, upRowIndex];
18             }
19         }
20 
21         /// <summary>
22         /// 向下遍历
23         /// </summary>
24         /// <param name="sender"></param>
25         /// <param name="e"></param>
26         private void btn_Down_Click(object sender, EventArgs e)
27         {
28              //获取下一行的索引
29             int nextRowIndex = this.dgv_PropDemo.CurrentCell.RowIndex + 1;
30             if (nextRowIndex > this.dgv_PropDemo.RowCount - 1)
31             {
32                 this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, 0];
33             }
34             else
35             {
36                 this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, nextRowIndex];
37             }
38         }
复制代码

 

posted @   .NET开发菜鸟  阅读(8331)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示