你是想獲取總行數(shù)?還是選中行和列的索引?
我們提供的服務(wù)有:成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、昂仁ssl等。為成百上千企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的昂仁網(wǎng)站制作公司
獲取總行數(shù):dataGridView1.Rows.Count;
獲取當(dāng)前選中行索引:int i = this.dataGridView1.CurrentRow.Index;
獲取當(dāng)前選中列索引:int j = this.dataGridView1.CurrentCell.ColumnIndex;
假如一個(gè)表有好多個(gè)taget:
我們要拿Southern CN和KDC之間的Target的行數(shù)
思路:我們先拿Southern CN的行數(shù),然后拿KDC的行數(shù)
dt.Rows.
IndexOf(dt.Rows.Cast(Of System.Data.DataRow).
Where(Function(r) r(3).ToString.StartsWith("Target") And dt.Rows.IndexOf(r) iSCN And dt.Rows.IndexOf(r) iKDCRow).First()) + 1
在窗體上加上三個(gè)標(biāo)簽控件:Label1、Label2、Label3
Private?Sub?DataGridView1_MouseUp(ByVal?sender?As?Object,?ByVal?e?As?System.Windows.Forms.MouseEventArgs)?Handles?DataGridView1.MouseUp
Dim?counter?As?Integer
Dim?SelectedCellTotal?As?Integer?=?0
Dim?SelectedCellCount?As?Integer?=?0
For?counter?=?0?To?(DataGridView1.SelectedCells.Count?-?1)
If?DataGridView1.SelectedCells(counter).FormattedValueType?Is?_
Type.GetType("System.String")?Then
Dim?value?As?String?=?Nothing
If?(DataGridView1.IsCurrentCellDirty?=?True)?Then
value?=?DataGridView1.SelectedCells(counter).EditedFormattedValue.ToString()
Else
value?=?DataGridView1.SelectedCells(counter).FormattedValue.ToString()
End?If
If?value?IsNot?Nothing?Then
If?Not?value.Length?=?0?Then
SelectedCellTotal?=?SelectedCellTotal?+?Integer.Parse(value)
SelectedCellCount?=?SelectedCellCount?+?1
End?If
End?If
End?If
Next
Label1.Text?=?"選中的單元格個(gè)數(shù)為:?"??SelectedCellCount.ToString()
Label2.Text?=?"單元格里數(shù)據(jù)之和為:?"??SelectedCellTotal.ToString()
Label3.Text?=?"選中的單元格行數(shù)為:"??DataGridView1.SelectedRows.Count.ToString()
End?Sub
仿造我的例子,你自己做做看1)設(shè)計(jì)一個(gè)類似的界面(我只有兩個(gè)字段) 2)單擊GridView的右上角小箭頭,去掉逗允許編輯地(黑色框部分): 3)然后把GridView的屬性做如下改動(dòng): 4)在Form1中增加綁定數(shù)據(jù)的代碼(我是模擬的)Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load '動(dòng)態(tài)增加一個(gè)表格,綁定到GridView上
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("name", GetType(String))
dt.Columns(0).AutoIncrement = True
dt.Columns(0).AutoIncrementSeed = 1
dt.Columns(0).AutoIncrementStep = 1 '模擬數(shù)據(jù)庫數(shù)據(jù)
Dim row As DataRow For i As Integer = 1 To 10
row = dt.NewRow
row("name") = "name" i
dt.Rows.Add(row)
Next
dt.AcceptChanges() DataGridView1.DataSource = dt End Sub 5)然后使用SelectionChanged事件這樣編碼:Private Sub DataGridView1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
If (DataGridView1.SelectedRows IsNot Nothing AndAlso DataGridView1.SelectedRows.Count 0) Then
'只選擇單行,因此取第一行
txtId.Text = DataGridView1.SelectedRows(0).Cells(0).Value
txtName.Text = DataGridView1.SelectedRows(0).Cells(1).Value
End If
End Sub