我使用以下方法填充了datagridview,我也添加了按钮列:
private void populatedatagridview()
{
categorieslist();
productgridview.RowTemplate.Height = 130;
var productsbycount = axe.products.GroupBy(x => x.product_Id).Select(a => new
{
productid = a.Key,
productnam = a.FirstOrDefault().product_Name,
productimage = a.FirstOrDefault().product_Image,
productdescr = a.FirstOrDefault().product_Description,
stockavailable = a.LongCount(),
productprice = a.FirstOrDefault().product_Price
});
productbindingsource.DataSource = productsbycount;
productgridview.DataSource = productbindingsource;
DataGridViewButtonColumn column = new DataGridViewButtonColumn();
productgridview.Columns.Add(column);
column.FlatStyle = FlatStyle.System;
column.DefaultCellStyle.ForeColor = Color.ForestGreen;
column.DefaultCellStyle.Padding = new Padding(10,48,10,48);
column.Text = "Buy";
column.HeaderText = "Buy";
column.UseColumnTextForButtonValue = true;
column.Name = "btnbuy";
productgridview.Columns[0].Visible = false;
for (int i = 0 ; i < productgridview.Columns.Count; i++)
if (productgridview.Columns[i] is DataGridViewImageColumn)
{
((DataGridViewImageColumn)productgridview.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
break;
}
}
我的问题是每当我调用此函数时,datagrid视图会添加另一个按钮列,因此它会自动增加按钮列的数量。
我有一个组合框我希望填充datagrid视图取决于组合框文本。那时我还要调用这个函数。
不幸的是,无论何时调用此函数,它都会反复自动添加按钮列。有人请帮忙吗?
答案 0 :(得分:2)
更改此块:
DataGridViewButtonColumn column = new DataGridViewButtonColumn();
productgridview.Columns.Add(column);
column.FlatStyle = FlatStyle.System;
column.DefaultCellStyle.ForeColor = Color.ForestGreen;
column.DefaultCellStyle.Padding = new Padding(10, 48, 10, 48);
column.Text = "Buy";
column.HeaderText = "Buy";
column.UseColumnTextForButtonValue = true;
column.Name = "btnbuy";
为:
if (productgridview.Columns["btnbuy"] == null)
{
DataGridViewButtonColumn column = new DataGridViewButtonColumn();
productgridview.Columns.Add(column);
column.FlatStyle = FlatStyle.System;
column.DefaultCellStyle.ForeColor = Color.ForestGreen;
column.DefaultCellStyle.Padding = new Padding(10, 48, 10, 48);
column.Text = "Buy";
column.HeaderText = "Buy";
column.UseColumnTextForButtonValue = true;
column.Name = "btnbuy";
}
答案 1 :(得分:0)
每次调用方法时都会获得额外的列,因为您的方法会添加列:
productgridview.Columns.Add(column);
我会将格式化DataGridView的代码与数据绑定它的代码分开。运行格式化网格的代码只需运行一次,并在需要时运行数据绑定它的代码。
您的populatedatagridview
方法实际上做了两件事:查询数据源并将查询结果绑定到网格,并通过添加列并设置某些列的ImageLayout属性来更改DataGridView的外观
我将删除所有将网格外观更改为新方法的代码,并将其调用一次,可能是在Form Load中。这使得populatedatagridview
只负责填充DataGridView。