我在綁定到地址列表的WinForm應用程序中有一個datagrid。地址列表很長,所以我必須滾動來選擇我想要的地址。但是,在滾動並找到我想要的地址並將其選中後,數據網格將選擇表格第一次加載時位於網格中相同位置的地址。我想知道我做錯了什麼,以及如何得到我想要的結果。Datagrid在滾動後選擇了錯誤的行
//
// bindingSource1
//
private System.Windows.Forms.BindingSource bindingSource1;
this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components);
this.bindingSource1.DataSource = typeof(ViewModels.ListAddressViewModel);
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToOrderColumns = true;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.HouseNumber,
this.Prefix,
this.StreetName,
this.StreetType,
this.StreetSuffix,
this.SecondaryType,
this.SecondaryNumber,
this.City,
this.State,
this.ZipCode});
this.dataGridView1.DataBindings.Add(new System.Windows.Forms.Binding("DataSource", this.bindingSource1, "AddressList", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(0, 50);
this.dataGridView1.MultiSelect = false;
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.ShowCellErrors = false;
this.dataGridView1.ShowCellToolTips = false;
this.dataGridView1.ShowEditingIcon = false;
this.dataGridView1.ShowRowErrors = false;
this.dataGridView1.Size = new System.Drawing.Size(1014, 421);
this.dataGridView1.TabIndex = 2;
this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
//Selection Change Handler
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
_vm.SelectedAddress = (Address)dataGridView1.SelectedRows[0].DataBoundItem;
}
}
//My View Model (_vm)
public class ListAddressViewModel
{
public IList<Address> AddressList { get; set; }
private IAddressRepository _repo;
public Address SelectedAddress {get;set;}
public ListAddressViewModel()
{
AddressList = new List<Address>();
}
public ListAddressViewModel(IAddressRepository AddrRepo)
:this()
{
_repo = AddrRepo
init();
}
private void init()
{
if(_repo != null)
{
AddressList = _repo.FindAll();
}
}
... etc..
}
你需要記錄你的'bindingSource1'對象和什麼是'_vm'。 – LarsTech
添加了Bindingsource和_vm代碼。正如你所看到的,_vm只是ViewModel的簡單實現。 – Scott
如果您可以向我們提供我們可以使用的源代碼,那會很好嗎?也許這可能是您的程序的一些有限的子集,它不會顯示任何專有數據,但仍然存在內部錯誤? – Alexey