フォームにdatagridviewを埋め込みを使用しています。
フォームの読み込み時にはreadonlyにして
AllowUserToAddRows = Falseとしているのですが、
「新規作成」ボタン押すと、行が一番下に追加され、
1行のみ編集可能な状態にしたいと思っています。
が、AllowUserToAddRows = Falseにすると
新規作成した行に何か入力するとその下の行も勝手に
できてしまいます。
これを1行のみ入力できるようにならないでしょうか。
『BindingSource』を使うとか。
DataGridView と BindingSource を 1つずつ、それに、
TextBox と Button を 3 つずつ貼っておいてください。
'-----------------
Public Class Form1
Private table As DataTable
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
table = New DataTable()
table.Columns.Add("列1")
table.Columns.Add("列2")
table.Columns.Add("列3")
table.Rows.Add("1-1", "1-2", "1-3")
table.Rows.Add("2-1", "2-2", "2-3")
table.Rows.Add("3-1", "3-2", "3-3")
table.Rows.Add("4-1", "4-2", "4-3")
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
Button1.Text = "新規"
Button2.Text = "更新"
Button3.Text = "キャンセル"
TextBox1.DataBindings.Add(New Binding("Text", BindingSource1, "列1", True, DataSourceUpdateMode.OnPropertyChanged))
TextBox2.DataBindings.Add(New Binding("Text", BindingSource1, "列2", True, DataSourceUpdateMode.OnPropertyChanged))
TextBox3.DataBindings.Add(New Binding("Text", BindingSource1, "列3", True, DataSourceUpdateMode.OnPropertyChanged))
DataGridView1.AllowUserToAddRows = False
DataGridView1.ReadOnly = True
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Button1.Enabled = False
BindingSource1.AddNew()
End Sub
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
BindingSource1.EndEdit()
Button1.Enabled = True
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
BindingSource1.CancelEdit()
Button1.Enabled = True
End Sub
Private Sub DataGridView1_RowEnter(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.RowEnter
If e.RowIndex = -1 Then
Return
End If
Dim rowView As DataRowView
rowView = DirectCast(DataGridView1.Rows(e.RowIndex).DataBoundItem, DataRowView)
If rowView.IsNew Then
Return
ElseIf rowView.IsEdit Then
BindingSource1.CancelEdit()
End If
End Sub
End Class
'-----------------
実際の運用では、Form1_Load 内のほとんどの処理(DataBindins.Add等)は、
(コードではなく)デザイナ上で設定することになるでしょう。
回答ありがとうございます。
BindingSourceを使用して、新規ボタンの箇所に
BindingSource.AddNew()と記入し、
rowenter部分をそのままコピーさせてもらいましたが、
「新規」ボタン押下し、新しい行は追加されるのですが、
カーソルが当たっても新規に追加した行のフィールドは
編集不可のままとなってしまいます。
解決しました。
ありがとうございました。
ツイート | ![]() |