C#操作DataGridView獲取或設(shè)置當(dāng)前單元格的內(nèi)容
當(dāng)前單元格指的是DataGridView焦點(diǎn)所在的單元格,它可以通過DataGridView對(duì)象的CurrentCell屬性取得。如果當(dāng)前單元格不存在的時(shí)候,返回null。
取得當(dāng)前單元格的內(nèi)容:
object obj = this.dgv_PropDemo.CurrentCell.Value;
注:返回值是object類型的。
取得當(dāng)前單元格的列Index:
int columnIndex = this.dgv_PropDemo.CurrentCell.ColumnIndex;
取得當(dāng)前單元格所在的行的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開始的。
當(dāng)前的單元格可以通過設(shè)定DataGridView對(duì)象的CurrentCell來改變。
DataGridView1.CurrentCell=DataGridView1[int columnIndex,int rowIndex];
注:如果DataGridVIew的選中模式是行選擇,那么會(huì)選中當(dāng)前單元格所在的整行。否則只會(huì)選中設(shè)置的當(dāng)前單元格。
將CurrentCell設(shè)置為Null可以取消激活的當(dāng)前單元格。
示例:設(shè)置第一行第二列為當(dāng)前的CurrentCell
this.dgv_PropDemo.CurrentCell = this.dgv_PropDemo[1, 0];
示例:通過向上和向下實(shí)現(xiàn)遍歷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];
}
}到此這篇關(guān)于C#操作DataGridView獲取或設(shè)置當(dāng)前單元格內(nèi)容的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Unity實(shí)現(xiàn)攻擊范圍檢測(cè)并繪制檢測(cè)區(qū)域
這篇文章主要介紹了Unity實(shí)現(xiàn)攻擊范圍檢測(cè)并繪制檢測(cè)區(qū)域,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
Winform圓形環(huán)繞的Loading動(dòng)畫實(shí)現(xiàn)代碼
這篇文章主要介紹了Winform圓形環(huán)繞的Loading動(dòng)畫實(shí)現(xiàn)代碼,有需要的朋友可以參考一下2014-01-01
C#生成不重復(fù)隨機(jī)數(shù)列表實(shí)例
C#生成不重復(fù)隨機(jī)數(shù)列表實(shí)例的代碼,需要的朋友可以參考一下2013-02-02
C#自動(dòng)類型轉(zhuǎn)換與強(qiáng)制類型轉(zhuǎn)換的講解
今天小編就為大家分享一篇關(guān)于C#自動(dòng)類型轉(zhuǎn)換與強(qiáng)制類型轉(zhuǎn)換的講解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
C#中無邊框窗體移動(dòng)的簡(jiǎn)單實(shí)例
拖動(dòng)無邊框窗體Form至桌面任何位置,有需要的朋友可以參考一下2013-08-08

