DataRowViewを使いDataGridViewの現在の行(または任意の行)からソース元のDataTableのDataRowを取得します。
Dim dgr As System.Windows.Forms.DataGridViewRow = Me.DataGridView1.CurrentRow
Dim drv As System.Data.DataRowView = CType(dgr.DataBoundItem, System.Data.DataRowView)
Dim dr As DataRow = CType(drv.Row, System.Data.DataRow)
使用例:フォームにDataGridViewとButtonを配置します。
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'サンプルデータテーブル
Dim dt As New DataTable
dt.Columns.Add("NO", Type.GetType("System.Double"))
dt.Columns.Add("CATEGORY1", Type.GetType("System.String"))
dt.Columns.Add("CATEGORY2", Type.GetType("System.String"))
dt.Columns.Add("CATEGORY3", Type.GetType("System.String"))
dt.Columns.Add("NAME", Type.GetType("System.String"))
dt.Columns.Add("VAL1", Type.GetType("System.Double"))
dt.Columns.Add("VAL2", Type.GetType("System.Double"))
dt.Columns.Add("VAL3", Type.GetType("System.Double"))
dt.Columns.Add("VAL4", Type.GetType("System.Double"))
dt.Columns.Add("VAL5", Type.GetType("System.Double"))
Dim r As New System.Random(1000)
Dim no As Integer = 0
For j1 = 0 To 100
For j2 = 0 To 5
For j3 = 0 To 3
Dim nr As DataRow = dt.NewRow
nr("NO") = no
nr("CATEGORY1") = "分類" & j1.ToString("00")
nr("CATEGORY2") = "分類" & j2.ToString("00")
nr("CATEGORY3") = "分類" & j3.ToString("00")
nr("NAME") = "名前" & j1.ToString("00") & j2.ToString("00") & j3.ToString("00")
nr("VAL1") = r.Next(10000)
nr("VAL2") = r.Next(10000)
nr("VAL3") = r.Next(10000)
nr("VAL4") = r.Next(10000)
nr("VAL5") = r.Next(10000)
dt.Rows.Add(nr)
no += 1
Next
Next
Next
Me.DataGridView1.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dgr As System.Windows.Forms.DataGridViewRow = Me.DataGridView1.CurrentRow
Dim drv As System.Data.DataRowView = CType(dgr.DataBoundItem, System.Data.DataRowView)
Dim dr As DataRow = CType(drv.Row, System.Data.DataRow)
Console.WriteLine("---------------------------------------------------------")
For i = 0 To dr.Table.Columns.Count - 1
Console.WriteLine(dr.Table.Columns(i).ColumnName.ToString & " = " & dr.Item(i).ToString)
Next
End Sub
End Class
|
実行結果 |
0 件のコメント:
コメントを投稿