我正在尝试自定义 DataGridView 类以在所有行下方有一个按钮。
到目前为止,我已经向 DataGridView.Controls 添加了一个按钮。
此按钮的位置在每个添加/删除行、DataGridView 调整大小和滚动时计算。
这是有效的,但是有一个问题。在 DataGridView 调整大小或滚动时,当 DataGridView 的底部边缘位于最后一行的正下方时,按钮根本不可见或只是部分不可见。
有没有办法让按钮始终可见?
我试过设置滚动条位置和 FirstDisplayedScrollingRowIndex。这是行不通的。 不幸的是,这个项目不可能添加一个全新的行。
添加按钮:
buttonAddRow.Height = 17;
buttonAddRow.Text = "+";
buttonAddRow.FlatStyle = FlatStyle.System;
buttonAddRow.Font = new Font(buttonAddRow.Font.FontFamily, 6.75F);
buttonAddRow.Click += ButtonAddRow_Click;
dataGridView.Controls.Add(buttonAddRow);
位置:
private void setLocation()
{
if (dataGridView.FirstDisplayedCell != null)
{
int positionY = 0;
positionY += dataGridView.ColumnHeadersHeight;
var visibleRowsCount = dataGridView.DisplayedRowCount(true);
var firstDisplayedRowIndex = dataGridView.FirstDisplayedCell.RowIndex;
var lastvisibleRowIndex = (firstDisplayedRowIndex + visibleRowsCount) - 1;
for (int rowIndex = firstDisplayedRowIndex; rowIndex <= lastvisibleRowIndex; rowIndex++)
{
positionY += dataGridView.Rows[rowIndex].Height;
}
buttonAddRow.Location = new Point(dataGridView.ClientRectangle.X, dataGridView.ClientRectangle.Y + positionY);
buttonAddRow.Visible = true;
}
}
最佳答案
下面是一些代码,用于创建我之前描述的“按钮行”,并将此按钮行添加到 DataGridView
的顶部、底部和第 4 行。如图所示,这个按钮只在第一列。如果要在所有列中显示按钮,则必须实现 OnPaint 方法来调整此行。但是,看图片,如果用户向下滚动,则顶部按钮行将不可见,这是您必须在用户向下滚动时将按钮行保持在顶部的位置。如果这就是您要查找的内容,那么您最终会得到一个始终显示在网格顶部的静态按钮。再次将此按钮放在网格上方和外侧将完成同样的事情,而且工作要少得多。
下面的代码使用了一个包含 3 个文本列的 DataGridView
。
private void Form1_Load(object sender, EventArgs e) {
FillGrid();
InsertButtonRow(0);
InsertButtonRow(4);
InsertButtonRow(dataGridView.Rows.Count -1);
}
private void FillGrid() {
for (int i = 1; i < 15; i++) {
dataGridView.Rows.Add("Row" + i + "C1", "Row" + i + "C2", "Row" + i + "C3");
}
}
private void InsertButtonRow(int rowIndex) {
if (rowIndex >= 0 && rowIndex < dataGridView.Rows.Count) {
DataGridViewButtonCell buttonCell = new DataGridViewButtonCell();
buttonCell.Value = "+";
buttonCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
DataGridViewRow row = (DataGridViewRow)dataGridView.Rows[0].Clone();
row.Cells[0] = buttonCell;
dataGridView.Rows.Insert(rowIndex, row);
}
}
关于c# - 将按钮添加到 DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42975227/