DataGridView取得或者修改当前单元格的内容

本文介绍了如何在C#和VB.NET中使用DataGridView控件的基本操作,包括获取当前单元格的内容及其行列索引,以及如何设定当前单元格。同时提供了通过按钮点击事件实现单元格遍历的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当前单元格指的是 DataGridView 焦点所在的单元格,它可以通过 DataGridView 对象的 CurrentCell 属性取得。如果当前单元格不存在的时候,返回Nothing(C#null)
[VB.NET]
取得当前单元格内容
Console.WriteLine(DataGridView1.CurrentCell.Value)
取得当前单元格的列 Index
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex)
取得当前单元格的行 Index
Console.WriteLine(DataGridView1.CurrentCell.RowIndex)
 
[C#]
// 取得当前单元格内容
Console.WriteLine(DataGridView1.CurrentCell.Value);
// 取得当前单元格的列 Index
Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);
// 取得当前单元格的行 Index
Console.WriteLine(DataGridView1.CurrentCell.RowIndex);

另外,使用 DataGridView.CurrentCellAddress 属性(而不是直接访问单元格)来确定单元格所在的行:DataGridView.CurrentCellAddress.Y 和列:DataGridView.CurrentCellAddress.X 。这对于避免取消共享行的共享非常有用。

当前的单元格可以通过设定 DataGridView 对象的 CurrentCell 来改变。可以通过 CurrentCell 来设定
DataGridView 
的激活单元格。将 CurrentCell 设为 Nothing(null) 可以取消激活的单元格。
[VB.NET]
设定 (0, 0)  为当前单元格
DataGridView1.CurrentCell = DataGridView1(0, 0)
 
[C#]
// 设定 (0, 0)  为当前单元格
DataGridView1.CurrentCell = DataGridView1[0, 0];

在整行选中模式开启时,你也可以通过 CurrentCell 来设定选定行。
        /// <summary>
        
/// 向下遍历
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        
private void button4_Click(object sender, EventArgs e)
        
{
            
int row = this.dataGridView1.CurrentRow.Index + 1;
            
if (row > this.dataGridView1.RowCount - 1)
                row = 0;
            
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];  
        }

        
/// <summary>
        
/// 向上遍历
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>
        
private void button5_Click(object sender, EventArgs e)
        
{
            
int row = this.dataGridView1.CurrentRow.Index - 1;
            
if (row < 0)
                row = 
this.dataGridView1.RowCount - 1;
            
this.dataGridView1.CurrentCell = this.dataGridView1[0, row];  
        }

注意: this.dataGridView 的索引器的参数是: columnIndex, rowIndex 或是 columnName, rowIndex
这与习惯不同。




本文转自 qianshao 51CTO博客,原文链接:http://blog.51cto.com/qianshao/201775,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值