今日、会社のメンバーからDataGridViewに「ボタン列を追加したいんだけど」と相談を受けました。
「HIRO's.NETにやり方載ってないね」との突っ込みが... 確かにその通り載っていません。
実際には、下記のようなやり方で実現できます。
DataGridViewButtonColumnインスタンス(これがボタン列になります)を作成して、DataGridViewに追加すればOKです。
ボタンがクリックされると、CellContentClickイベントが発生するので、引数e(DataGridViewCellEventArgs)のe.RowIndexやe.ColumnIndexを調べればどのボタンが押されたかがわかります。
実行例は下図のような感じです。
コードは下記の通りです。
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load AddButton() End Sub Private Sub AddButton() Dim dtSet As New DataSet() dtSet.ReadXml("C:\Work\Test.xml") DataGridView1.DataSource = dtSet.Tables(0) 'DataGridViewButtonColumnを作成する Dim colBtn As New DataGridViewButtonColumn() '列名とボタン名を設定 colBtn.Name = "ボタン列" colBtn.Text = "ボタンです" '所有側の列のテキストを、セル内のボタンに表示 colBtn.UseColumnTextForButtonValue = True 'DataGridViewに追加する DataGridView1.Columns.Add(colBtn) End Sub Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick If DirectCast(sender, DataGridView).Columns(e.ColumnIndex).Name = "ボタン列" Then MessageBox.Show((e.RowIndex + 1).ToString() & "のボタンが押された") End If End Sub
Theme design by Jelle Druyts
Pick a theme: BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2 BlogXP business calmBlue Candid Blue dasBlog dasblogger DirectionalRedux Discreet Blog Blue Elegante essence Just Html MadsSimple Mobile Mono Movable Radio Blue Movable Radio Heat nautica022 orangeCream Portal Project84 Project84Grass Slate Sound Waves Tricoleur useit.com Voidclass2
Powered by: newtelligence dasBlog 2.0.7226.0
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009, HIRO
E-mail