在Button Click上的GridView winform中添加新行

时间:2012-10-20 10:33:36

标签: c#-4.0

在Button Click上的GridView winform中添加新行。 需要在网格中使用单个按钮而不是DataGridViewButtonColumn

2 个答案:

答案 0 :(得分:1)

您可以使用

添加它

GridView1.DataSource = datatable;

然后按此

添加新行

datatable.Rows.Add();

这将添加新行并将控制ID提供给add()。

答案 1 :(得分:1)

use this 

public partial class Form1 : Form
    {
        Button textBoxDgv1 = new Button();
        Label labelDgv1 = new Label();
the next is on the Form_Load event

private void Form1_Load(object sender, EventArgs e)
        {
            labelDgv1.Text = "Delete";
            labelDgv1.Height = 20;
            labelDgv1.AutoSize = false;
            labelDgv1.BorderStyle = BorderStyle.FixedSingle;
            labelDgv1.TextAlign = ContentAlignment.MiddleCenter;
            int Xdgv1 = this.dataGridView1.GetCellDisplayRectangle(2, -1, true).Location.X;
            labelDgv1.Width = this.dataGridView1.Columns[2].Width + Xdgv1;
            labelDgv1.Location = new Point(0, this.dataGridView1.Height - textBoxDgv1.Height);
            this.dataGridView1.Controls.Add(labelDgv1);

and one more section is in dataGridView1_CellPainting

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
       int sum = 0;
       for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
       {
           if (dataGridView1.Rows[i].Cells[3].Value != string.Empty)
           {
               sum += Convert.ToInt32(this.dataGridView1[3, i].Value);
           }
       }
           textBoxDgv1.Text = sum.ToString();
           int Xdgvx = this.dataGridView1.GetCellDisplayRectangle(2, -1, true).Location.X;
           labelDgv1.Width = this.dataGridView1.Columns[2].Width + Xdgvx;
           labelDgv1.Location = new Point(0, this.dataGridView1.Height - textBoxDgv1.Height);
           textBoxDgv1.Width = this.dataGridView1.Columns[3].Width;
           Xdgvx = this.dataGridView1.GetCellDisplayRectangle(3, -1, true).Location.X;
           textBoxDgv1.Location = new Point(Xdgvx, this.dataGridView1.Height - textBoxDgv1.Height);
}