日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#操作DataGridView獲取或設置當前單元格的內容_C#教程

作者:.NET開發菜鳥 ? 更新時間: 2022-04-30 編程語言

當前單元格指的是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

/// 
        /// 向上遍歷
        /// 
        /// 
        /// 
        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];
            }
        }

        /// 
        /// 向下遍歷
        /// 
        /// 
        /// 
        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];
            }
        }

原文鏈接:https://www.cnblogs.com/dotnet261010/p/6748378.html

欄目分類
最近更新