[英]Adding button to DataGridView
我正在嘗試自定義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方法來調整此行。 但是,從圖片上看,如果用戶向下滾動,則頂部的按鈕行將不可見,這是您必須在用戶向下滾動時實現將按鈕行保持在頂部的位置。 如果這是您要查找的內容,那么最終得到的是一個STATIC按鈕,該按鈕始終顯示在網格頂部。 再次在網格上方和外部放置此按鈕,將花費更少的精力完成相同的任務。
下面的代碼使用帶有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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.