Hi
I'm focusing on "The user should be able to change the selected item in FooContainer by changing the selection in the DataGridView."
The following solution lets the user select items by clicking the cell, and the following event sets the according item in the bound data collection to the
SelectedItem
in your
FooContainer
-class.
Your should ask you self if the
FooContainer
-class really is needed.
Please remember to vote and comment!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Test_DataBinding
{
public partial class Form1 : Form
{
private FooContainer _foos = new FooContainer();
public Form1()
{
InitializeComponent();
dgvFoo.DataSource = _foos.Items;
dgvFoo.CellClick += new DataGridViewCellEventHandler(dgvFoo_CellClick);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
}
void dgvFoo_CellClick(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvFoo.SelectedRows)
{
Foo myFoo = row.DataBoundItem as Foo;
if (myFoo != null)
{
_foos.SelectedItem = myFoo;
}
}
}
public class FooContainer
{
private BindingList<foo> _fooList = new BindingList<foo>();
private Foo _selected = null;
public FooContainer()
{
_fooList.Add(new Foo("First"));
_fooList.Add(new Foo("Second"));
_fooList.Add(new Foo("Third"));
}
public BindingList<foo> Items
{
get { return (_fooList); }
}
public Foo SelectedItem
{
get { return (_selected); }
set { _selected = value; }
}
}
public class Foo
{
private string _name = string.Empty;
public Foo(string name)
{
_name = name;
}
public string Name
{
get { return (_name); }
}
public override string ToString()
{
string name = _name;
if(name==string.Empty)
name = "NoName";
return (name + "(" + this.GetType().ToString() + ")");
}
}
}</foo></foo></foo>