Winform cs代码操作DataGridView使某一列添加多个button控件

1、新建winform程序,添加一个datagridview


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dataGridView1.Columns.Add("first", "first");
            this.dataGridView1.Columns.Add("second", "second");
            this.dataGridView1.Columns.Add("third", "third"); 
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            for (int i = 0; i < 15; i++)
                this.dataGridView1.Rows.Add();

            for (int i = 0; i < 15; i++)
            {
                Button[] btn = new Button[2];
                btn[0] = new Button();
                btn[0].Text = "操作1";
                btn[1] = new Button();
                btn[1].Text = "操作2";
                this.dataGridView1.Controls.Add(btn[0]);
                this.dataGridView1.Controls.Add(btn[1]);
                Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(2, i, false);
                btn[0].Size = btn[1].Size = new Size(rect.Width / 2, rect.Height);
                btn[0].Location = new Point(rect.Left, rect.Top);
                btn[1].Location = new Point(rect.Left + btn[0].Width, rect.Top);
                btn[0].Click += new EventHandler(CustomBtn_Click);
                btn[1].Click += new EventHandler(CustomBtn_Click);
            }
        }
        void CustomBtn_Click(object sender, EventArgs e)
        {
            MessageBox.Show((sender as Button).Text);
        }
         
        //  滚动DataGridView时调整Button位置
        private void DataGridView_Scroll(object sender, ScrollEventArgs e)
        {
        }
        //  改变DataGridView列宽时调整Button位置
        private void DataGridView_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
        }
    }

实际效果 

Winform cs代码操作DataGridView使某一列添加多个button控件_第1张图片

 

你可能感兴趣的:(编程实用方法,c#,开发语言,后端,winform,datagridview)