怎样在DataGridView的Cell中添加多个按钮,并且能实现在DataGridView出现滚动条后,Button按钮能够和Cell连动?

解决方案 »

  1.   


    //先创建一个Button
    private Button btn = new Button();
    private int m_RowIndex; //所在行的索引
    先给dataGridView添加一个CellEnter事件,收到输入焦点时发生。private void dataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
    this.dataGridView.Controls.Clear();//移除所有控件
    btn.Click -= new EventHandler(btnTimeStart_Click);
    //判断单元格是否是"按钮"列
    if (e.ColumnIndex.Equals(dataGridView.Columns["按钮"].Index))
    {
    //Button btn = new Button();//创建Buttonbtn
    btn.Text = "开始";//设置button文字
    btn.Font = new Font("宋体", 9);//设置文字格式
    btn.FlatStyle = FlatStyle.Flat;
    btn.Visible = true;//设置控件允许显示
    //获取单元格宽并设置为btn的宽
    btn.Width = dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Width;
    //获取单元格高并设置为btn的高                    
    btn.Height = dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Height;
    //为btn添加单击事件
    btn.Click += new EventHandler(btnTimeStart_Click);
    //dataGridView中添加控件btn
    dataGridView.Controls.Add(btn);
                    //记录下所在行的索引
    m_RowIndex = e.RowIndex;
    //设置btn显示位置
    btn.Location = new Point(((dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Right) -
    (btn.Width)), dataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Y);
    }
    }
    然后再添加dataGridView的RowPostPaint事件,单元格行级绘制时发生。private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
    {
    //设置btn显示位置
    btn.Location = new Point(((dataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, true).Right) - (btn.Width)), dataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, true).Y);
    }
      

  2.   

    在cell中添加控件,控件可以包含子空间,添加几个按钮都行。
      

  3.   

    Button btn1 = new Button();
    btn1.Name = "btn";
    btn1.Text = "btn";
    btn1.Click+=new EventHandler(btn1_Click);
    this.dataGridView1.Controls.Add(btn1);
    public void btn1_Click(object sender, EventArgs e)
    {
      Button btn = (Button)(sender);
    }或
    DataGridViewButtonColumn dbc = new DataGridViewButtonColumn();
      

  4.   

    有一些问题,首先这个Cell里面会有不定的个数的按钮,用户在Cell中添加按钮就会增加一个按钮
      

  5.   

    2楼能说详细一点吗,怎么在Cell中直接添加控件?在DataGridView.Rows[i].Cells[j]中没有Add控件的方法啊!能说明一下吗?感谢!!!