私は DataGridView と格闘しています: INotifyPropertyChanged を実装するいくつかの単純なオブジェクトの BindingList があります。DataGridView のデータソースは、この BindingList に設定されます。「+」キーを押して、リストにオブジェクトを追加する必要があります。オブジェクトが追加されると、新しい行として表示され、現在の行になります。CurrentRow プロパティは読み取り専用であるため、すべての行を反復処理し、バインドされたアイテムが新しく作成されたオブジェクトかどうかを確認し、そうである場合は、この行を " Selected = true;
"に設定します。
問題: 新しいオブジェクトとそれによって新しい行が DataGridView に挿入されて選択されますが、それでも CurrentRow ではありません! この新しい行をマウスでクリックしない限り、CurrentRow にはなりません。
このテスト プログラムでは、「+」キーを使用して新しいオブジェクト (および行) を追加できます。「i」キーを使用すると、CurrentRow のデータ バインド オブジェクトが MessageBox に表示されます。
新しく追加されたオブジェクトを CurrentObject にする方法を教えてください。ご協力いただきありがとうございます!
サンプルは次のとおりです。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
BindingList<item> myItems;
public Form1()
{
InitializeComponent();
myItems = new BindingList<item>();
for (int i = 1; i <= 10; i++)
{
myItems.Add(new item(i));
}
dataGridView1.DataSource = myItems;
}
public void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add)
{
addItem();
}
}
public void addItem()
{
item i = new item(myItems.Count + 1);
myItems.Add(i);
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
if (dr.DataBoundItem == i)
{
dr.Selected = true;
}
}
}
private void btAdd_Click(object sender, EventArgs e)
{
addItem();
}
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add)
{
addItem();
}
if (e.KeyCode == Keys.I)
{
MessageBox.Show(((item)dataGridView1.CurrentRow.DataBoundItem).title);
}
}
}
public class item : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _id;
public int id {
get
{
return _id;
}
set
{
this.title = "This is item number " + value.ToString();
_id = value;
InvokePropertyChanged(new PropertyChangedEventArgs("id"));
}
}
private string _title;
public string title {
get
{
return _title;
}
set
{
_title = value;
InvokePropertyChanged(new PropertyChangedEventArgs("title"));
}
}
public item(int id)
{
this.id = id;
}
#region Implementation of INotifyPropertyChanged
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
#endregion
}
}