C#winform中给datagridview的每一行添加按钮

C#winform中给datagridview的每一行添加按钮
2024-11-09 13:39:23
推荐回答(4个)
回答1:

public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}

List strSourec = new List { "1", "2" };

void Form1_Load(object sender, EventArgs e)
{
foreach (string item in strSourec)
{
DataGridViewButtonColumn Column1 = new DataGridViewButtonColumn();
Column1.HeaderText = item;
this.dataGridView1.Columns.Add(Column1);
}
DataGridViewRow dr = new DataGridViewRow();

for (int i = 0; i < strSourec.Count; i++)
{
DataGridViewButtonCell dgvbc = new DataGridViewButtonCell();
dgvbc.Value = strSourec[i];
dr.Cells.Add(dgvbc);
}
dataGridView1.Rows.Add(dr);

this.dataGridView1.CellMouseDown += new DataGridViewCellMouseEventHandler(dataGridView1_CellMouseDown);
}

void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (dataGridView1[e.ColumnIndex, e.RowIndex].Value == null) return;
MessageBox.Show(dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString());
}

回答2:

在datagridview控件的右上角有一个三角形的按钮,在里面添加的时候有个选项你选择DataGridViewButtonColumn就可以了

回答3:

点击datagridview右上方的小箭头,编辑列——》添加列------类型选”DataGridViewButtonColumn“

回答4:

二楼正解~三楼的方法适合动态加载行时添加按钮,但是没必要这么复杂,按照lz的意思应该是某一列是按钮