views:

606

answers:

2

Hello.

I have not done a lot with WinForms so I wonder if someone could give me a little assistance with this. I have a DataGridView that is bond to a IList<>. When I delete a selected record from the collection (ILIST<>) I get the following exception:

"System.IndexOutOfRangeException:Index 3 does not have a value"

I think my binding is a little lame too. So maybe someone can give me a pointer here as well.

 public Form1()
    {
        InitializeComponent();
        empGrid.DataSource = stub.GetAllEmplyees();
        empGrid.Columns["FirstName"].Visible = true;
        StatusStrip.Text = "Employee Administration";

    }

What I would like to do is Delete a record and then refresh the DataGridGridView. What is the best way to define which properties you want to display in the columns?

Thanks a lot!

A: 

I do it this way, not using a DataSource as I had to customise the cell outputs.

// for inserts
foreach (var item in data)
{
    DataGridViewRow newRow = new DataGridViewRow();
    newRow.CreateCells(myDataGridView,
        your,
        data,
        for,
        each,
        cell,
        here);
    myDataGridView.Rows.Add(newRow);
}

    // for updates
    myDataGridView.Rows[rowIndex]
        .SetValues(cell,data,you,wish,to,change,here);

For deleting, I've encountered no problems using:

myDataGridView.Rows.RemoveAt(rowIndex);

myDataGridView.Refresh(); should work for refreshing.

GONeale
This is exactly what I needed. I already have a collection populated with my object instances. So this allowed me to just bind directly to that list. Perfect.. thank you sir!
Nick
No problem. I too found it cryptic when I first stepped into the world of DGV's, so after trimming away the fat I ended up with the above which I found to be simplest!
GONeale
A: 

Consider using a binding source (drag it from the toolbox and set the data source to the class type you need:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    List<MyClass> list = new List<MyClass>();
    private void Form1_Load(object sender, EventArgs e)
    {
        this.bindingSource1.DataSource = typeof(WindowsFormsApplication1.MyClass);

        list.AddRange(new MyClass[] {
            new MyClass { Column1 = "1", Column2 = "1" },
            new MyClass { Column1 = "2", Column2 = "2" }
            });

        bindingSource1.DataSource = list;
        bindingSource1.Add(new MyClass { Column1 = "3", Column2 = "3" });
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Here you remove rows without taking care of the representation:
        bindingSource1.RemoveAt(0); 
    }
}


class MyClass
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
}
Shimmy