C# WinForms上的DataGridView在我删除记录时引发异常

C# WinForms上的DataGridView在我删除记录时引发异常,c#,winforms,data-binding,datagridview,C#,Winforms,Data Binding,Datagridview,我在WinForms方面做得不多,所以我想知道是否有人可以在这方面给我一些帮助。我有一个绑定到IList的DataGridView。从集合(ILIST)中删除选定记录时,会出现以下异常: “System.IndexOutOfRangeException:索引3没有值” 我觉得我的装订也有点蹩脚。也许有人能给我一个指针 public Form1() { InitializeComponent(); empGrid.DataSource = stub.Get

我在WinForms方面做得不多,所以我想知道是否有人可以在这方面给我一些帮助。我有一个绑定到IList的DataGridView。从集合(ILIST)中删除选定记录时,会出现以下异常:

“System.IndexOutOfRangeException:索引3没有值”

我觉得我的装订也有点蹩脚。也许有人能给我一个指针

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

    }
我想做的是删除一条记录,然后刷新DataGridView。定义要在列中显示哪些特性的最佳方法是什么


非常感谢

我这样做,不使用数据源,因为我必须自定义单元格输出

// 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);
对于删除,我在使用时没有遇到任何问题:

myDataGridView.Rows.RemoveAt(rowIndex);

myDataGridView.Refresh()可以用于刷新。

考虑使用绑定源(从工具箱中拖动它,并将数据源设置为所需的类类型:

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; }
}
公共部分类表单1:表单
{
公共表格1()
{
初始化组件();
}
列表=新列表();
私有void Form1\u加载(对象发送方、事件参数e)
{
this.bindingSource1.DataSource=typeof(WindowsFormsApplication1.MyClass);
list.AddRange(新MyClass[]{
新MyClass{Column1=“1”,Column2=“1”},
新MyClass{Column1=“2”,Column2=“2”}
});
bindingSource1.DataSource=列表;
bindingSource1.Add(新的MyClass{Column1=“3”,Column2=“3”});
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
//在这里,您可以删除行而不考虑表示:
bindingSource1.RemoveAt(0);
}
}
类MyClass
{
公共字符串Column1{get;set;}
公共字符串Column2{get;set;}
}

这正是我所需要的。我已经有了一个包含我的对象实例的集合。因此,这允许我直接绑定到该列表。太好了。谢谢你,先生!没问题。当我第一次进入DGV的世界时,我也发现它很神秘,所以在修剪掉脂肪后,我最终得到了上面我发现最简单的东西!