DataGridView中间插入数据行

namespace WindowsFormsApp1
{
    public partial class Form2 : Form
    {
        private readonly BindingSource _bindingSource = 
            new BindingSource();

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn()
                { ColumnName = "id", DataType = typeof(int)});
            dt.Columns.Add(new DataColumn()
                { ColumnName = "FirstName", DataType = typeof(string) });
            dt.Columns.Add(new DataColumn()
                { ColumnName = "LastName", DataType = typeof(string) });

            dt.Rows.Add(1, "Mary", "Jones");
            dt.Rows.Add(2, "Ane", "Smith");
            dt.Rows.Add(3, "Jim", "Adams");
            dt.Rows.Add(4, "Hank", "Lebow");

            _bindingSource.DataSource = dt;
            dataGridView1.DataSource = _bindingSource;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (_bindingSource.Current == null) return;

            var dt = (DataTable) _bindingSource.DataSource;

            var nextId = dt.AsEnumerable()
                             .Select(dataRow => dataRow.Field<int>("Id"))
                             .Max() +1;

            var row = dt.NewRow();
            row["id"] = nextId;
            row["FirstName"] = "Karen";
            row["LastName"] = "Payne";

            dt.Rows.InsertAt(row, _bindingSource.Position);
        }
    }
}
posted @ 2019-04-26 17:06  Kyle0418  阅读(2268)  评论(0编辑  收藏  举报