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
/// <summary> /// 向上遍历 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Up_Click(object sender, EventArgs e) { //获取上一行的索引 int upRowIndex = this.dgv_PropDemo.CurrentCell.RowIndex - 1; if (upRowIndex < 0) { //选中最后一行 this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, this.dgv_PropDemo.RowCount - 1]; } else { this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, upRowIndex]; } } /// <summary> /// 向下遍历 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Down_Click(object sender, EventArgs e) { //获取下一行的索引 int nextRowIndex = this.dgv_PropDemo.CurrentCell.RowIndex + 1; if (nextRowIndex > this.dgv_PropDemo.RowCount - 1) { this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, 0]; } else { this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[0, nextRowIndex]; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)