Generic.List: How to set/get position/currentitem for DataGridView?
I'm currenty working on a DataGridView-extentsion with custom DataSource handling. If I bind a list to two normal System.Windows.Forms.DataGridView and 开发者_StackOverflow社区select an item in dataGridView1, dataGridView2 automatically also sets the position to the item.
If I assign a BindingSource I can handle the PositionChanged event, but a Generic.List doesn't have a CurrencyManager, so how does the dataGridView2 know the new position?
You want to get the current position of some DataGridView (having the as list as DataSource) from the List? Then the answer is: you cannot. The list knows nothing of the connected view - shown element included (of course)
Alternative to get the info from the DataGridView: subscribe to the SelectionChanged event of the DataGridView and set the index of the second accordingly - for both you should be able to use the CurrentCell-property
You cannot do such things as you described in your comments below without knowing something of the DataGridView. It's a different design - you could implement your own "ShowableList" or something and try creating your own DataGridView that shows the indicated item from your ShowableList and sets the ShownIndex in there too - but you have to do this yourself.
Finally i found the answer: BindingContext!
A simple example:
public class ModifiedCollection : BindingSource {
BindingSource Source {get;set;}
BindingManagerBase bmb;
Control Parent;
public ModifiedCollection(object Source, Control Parent) {
if ((this.Source = Source as BindingSource) == null) {
this.Source = new BindingSource();
this.Source.DataSource = Source;
}
this.Source.ListChanged += new ListChangedEventHandler(Source_ListChanged);
this.Parent = Parent;
this.Parent.BindingContextChanged += new EventHandler(Parent_BindingContextChanged);
}
void Parent_BindingContextChanged(object sender, EventArgs e) {
if (bmb != null) {
bmb.PositionChanged -= bmb_PositionChanged;
}
if (Parent.FindForm().BindingContext.Contains(this.Source.DataSource)) {
bmb = Parent.BindingContext[this.Source.DataSource];
if (bmb != null) {
bmb.PositionChanged += new EventHandler(bmb_PositionChanged);
}
}
}
}
精彩评论