这篇文章介绍了C#操作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];
}
}
到此这篇关于C#操作DataGridView获取或设置当前单元格内容的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
本文标题为:C#操作DataGridView获取或设置当前单元格的内容


基础教程推荐
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#中的Linq to JSON操作详解 2023-06-08
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C# 解析XML和反序列化的示例 2023-04-14
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- Unity shader实现高斯模糊效果 2023-01-16
- C#中 Json 序列化去掉null值的方法 2022-11-18
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- Unity 如何获取鼠标停留位置下的物体 2023-04-10