I want a Delete button at the end of each row of DataGridView
and by clicking that I want to remove the desired row from the binding list which is data source of my grid.
But I can't seem to do it I have created a button object in product class and instantiated it with the unique id to remove that object from list. but button is not showing in the row.
There are TextBoxes in the form and users can enter text, and when they press Add button, a new object of product is instantiated with the provided fields and then it is added to the BindingList
.
Finally this list is bound to the DataGridView
and details are shown in the grid. (I have done this part).
and at last by clicking save button the list is saved in the DB.
public class Product{
public string Brand { get; set; }
public int ProductPrice { get; set; }
public int Quantity { get; set; }
public product(string brand,int productPrice, int quantity){
this.Brand = brand;
this.ProductPrice = productPrice;
this.Quantity = quantity;
}
}
public partial class MainForm: Form{
.....
BindingList<Product> lProd = new BindingList<Product>();
private void btnAddProduct_Click(object sender, EventArgs e){
string Brand = txtProBrand.Text;
int Price = Convert.ToInt32(txtPrice.Text);
int Quantity = Convert.ToInt32(txtQuantity.Text);
Product pro = new Product(Brand, Price, Quantity);
lProd.Add(pro);
dataGridView1.DataSource = null;
dataGridView1.DataSource = lProd;
}
.....
}
To show a button on
DataGridView
rows, you should add aDataGridViewButtonColumn
to columns of your grid. Here is some common tasks which you should know when using button column:Add Button Column to DataGridView
To show a button on each row of your grid, you can add a
DataGridViewButtonColumn
to columns of your grid programmatically or using designer:Show Image on Button
If you prefer to draw image on button, you should have an image in a resource and then handle
CellPainting
event of your grid:Set Text of Button
You can use either of these options:
You can set
Text
property of yourDataGridViewButtonColumn
and also set itsUseColumnTextForButtonValue
totrue
, this way the text will display on each cells of that column.Also you can use
Value
property of cell:Also as another option, you can handle
CellFormatting
event of your grid. This way may be useful when you want to set different texts for buttons.Handle Click Event of Button
To hanlde clicks on button, you can handle
CellClick
orCellContentClick
event of your grid. Both events fires by click and by pressing Space key.Note
BindingList
you don't need to set datasource of grid to null and back to binding list with every change. TheBindingList
itself reflects changes to yourDataGridView
.