显示按钮DataGridView
行,你应该添加一个到网格的列。以下是使用按钮栏时应了解的一些常见任务:
- 将按钮列添加到 DataGridView
- 在按钮上显示图像
- 设置按钮文本
- 处理按钮的点击事件
将按钮列添加到 DataGridView
要在网格的每一行上显示一个按钮,您可以添加一个以编程方式或使用设计器到网格的列:
var deleteButton=new DataGridViewButtonColumn();
deleteButton.Name="dataGridViewDeleteButton";
deleteButton.HeaderText="Delete";
deleteButton.Text="Delete";
deleteButton.UseColumnTextForButtonValue=true;
this.dataGridView1.Columns.Add(deleteButton);
在按钮上显示图像
如果您喜欢在按钮上绘制图像,则应该在资源中拥有图像,然后处理您的网格事件:
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == dataGridView1.NewRowIndex || e.RowIndex < 0)
return;
if (e.ColumnIndex == dataGridView1.Columns["dataGridViewDeleteButton"].Index)
{
var image = Properties.Resources.DeleteImage; //An image
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
var x = e.CellBounds.Left + (e.CellBounds.Width - image.Width) / 2;
var y = e.CellBounds.Top + (e.CellBounds.Height - image.Height) / 2;
e.Graphics.DrawImage(image, new Point(x, y));
e.Handled = true;
}
}
设置按钮文本
您可以使用以下任一选项:
您可以设置Text
你的财产DataGridViewButtonColumn
并设置其UseColumnTextForButtonValue
to true
,这样文本将显示在该列的每个单元格上。
deleteButton.Text="Delete";
deleteButton.UseColumnTextForButtonValue=true;
您也可以使用Value
细胞性质:
this.dataGridView1.Rows[1].Cells[0].Value = "Some Text";
另外作为另一种选择,您可以处理您的网格的事件。当您想为按钮设置不同的文本时,这种方法可能很有用。
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//If this is header row or new row, do nothing
if (e.RowIndex < 0 || e.RowIndex == this.dataGridView1.NewRowIndex)
return;
//If formatting your desired column, set the value
if (e.ColumnIndex=this.dataGridView1.Columns["dataGridViewDeleteButton"].Index)
{
e.Value = "Delete";
}
}
处理按钮的点击事件
To hanlde clicks on button, you can handle or event of your grid. Both events fires by click and by pressing Space key.
void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
//if click is on new row or header row
if( e.RowIndex == dataGridView1.NewRowIndex || e.RowIndex < 0)
return;
//Check if click is on specific column
if( e.ColumnIndex == dataGridView1.Columns["dataGridViewDeleteButton"].Index)
{
//Put some logic here, for example to remove row from your binding list.
//yourBindingList.RemoveAt(e.RowIndex);
// Or
// var data = (Product)dataGridView1.Rows[e.RowIndex].DataBoundItem;
// do something
}
}
获取Click事件的记录数据
你有e.RowIndex
,然后就可以获取该行后面的数据:
var data = (Product)dataGridView1.Rows[e.RowIndex].DataBoundItem;
// then you can get data.Id, data.Name, data.Price, ...
您需要将其转换为重新计算的数据类型,例如Product
.
如果数据绑定已设置为使用 DataTable,则要转换的类型为DataRowView
.
您还可以使用dataGridView1.Rows[e.RowIndex].Cells[some cell index].Value
但是,要获取特定单元格的值DataBoundItem
更有意义。
Note
- 正如所提到的Ivan https://stackoverflow.com/users/5202563/ivan-stoev在评论中,当您使用
BindingList
您不需要在每次更改时将网格的数据源设置为 null 并返回到绑定列表。这BindingList
本身反映了你的变化DataGridView
.