Отключение столбца кнопки в представлении данных
У меня есть сетка данных с 4 столбцами, первые 2 столбца - столбцы комбинированного списка, третий столбец - столбец текстового поля, а 4-й столбец - столбец кнопки. При загрузке формы я должен отключить весь столбец кнопки сетки данных, а после этого выбрать первые три столбца и сохранить эти первые три столбца в базе данных после сохранения этого столбца кнопки в конкретной строке должен быть включен. Первые три столбца должны быть сохранены в базе данных, нажав кнопку. Пожалуйста, помогите мне, я столкнулся с этой проблемой в течение многих дней, вот код, который я использовал
private void SATAddTemplate_Load(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagrdADDTEMP.Rows)
{
DataGridViewButtonCell btn = (DataGridViewButtonCell)row.Cells[3];
btn.ReadOnly = true;
}
}
private void btnSaveSettings_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagrdADDTEMP.Rows)
{
DataGridViewButtonCell btn = (DataGridViewButtonCell)row.Cells[3];
btn.ReadOnly = false;
}
}
4 ответа
Вот некоторая помощь с проблемой установки Enabled
свойство кнопок, которые появляются в DataGridViewButtonColumn
,
Вам нужно будет продлить DataGridViewButtonColumn
создать свой собственный столбец DataGridView с отключаемыми кнопками. В этой статье на MSDN подробно описано, как это сделать.
В статье много кода, и я призываю вас внимательно посмотреть, но все, что вам действительно нужно, это скопировать и вставить в свой проект следующие классы, найденные в статье:
- DataGridViewDisableButtonColumn
- DataGridViewDisableButtonCell
Как только вы сделаете это, вы сможете добавить DataGridViewDisableButtonColumn
с вашего DataGridView. Используйте общественность Enabled
свойство выставлено в вашем пользовательском столбце, чтобы установить Enabled
свойство элемента управления каждой ячейки. Так как вы хотите установить Enabled
свойство всех кнопок в столбце, вы можете написать вспомогательный метод, который перебирает все строки в вашем DataGridView и устанавливает Enabled
имущество:
private void SetDGVButtonColumnEnable(bool enabled) {
foreach (DataGridViewRow row in dataGridView1.Rows) {
// Set Enabled property of the fourth column in the DGV.
((DataGridViewDisableButtonCell)row.Cells[3]).Enabled = enabled;
}
dataGridView1.Refresh();
}
Это дополнение к ответу Джея.
По запросу вот код, который я использовал для создания ячейки кнопки, которую можно отключить. Он включает в себя двойную буферизацию, так что кнопки не мерцают при прокрутке пользователя.
/// <summary>
/// Adapted from https://msdn.microsoft.com/en-us/library/ms171619.aspx. Double-buffering was added to remove flicker on re-paints.
/// </summary>
public class DataGridViewDisableButtonCell : DataGridViewButtonCell
{
private bool enabledValue;
public bool Enabled
{
get { return enabledValue; }
set
{
if (enabledValue == value) return;
enabledValue = value;
// force the cell to be re-painted
if (DataGridView != null) DataGridView.InvalidateCell(this);
}
}
// Override the Clone method so that the Enabled property is copied.
public override object Clone()
{
var cell = (DataGridViewDisableButtonCell) base.Clone();
cell.Enabled = Enabled;
return cell;
}
// By default, enable the button cell.
public DataGridViewDisableButtonCell()
{
enabledValue = true;
}
protected override void Paint(
Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates elementState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
// The button cell is disabled, so paint the border, background, and disabled button for the cell.
if (!enabledValue)
{
var currentContext = BufferedGraphicsManager.Current;
using (var myBuffer = currentContext.Allocate(graphics, cellBounds))
{
// Draw the cell background, if specified.
if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background)
{
using (var cellBackground = new SolidBrush(cellStyle.BackColor))
{
myBuffer.Graphics.FillRectangle(cellBackground, cellBounds);
}
}
// Draw the cell borders, if specified.
if ((paintParts & DataGridViewPaintParts.Border) == DataGridViewPaintParts.Border)
{
PaintBorder(myBuffer.Graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
}
// Calculate the area in which to draw the button.
var buttonArea = cellBounds;
var buttonAdjustment = BorderWidths(advancedBorderStyle);
buttonArea.X += buttonAdjustment.X;
buttonArea.Y += buttonAdjustment.Y;
buttonArea.Height -= buttonAdjustment.Height;
buttonArea.Width -= buttonAdjustment.Width;
// Draw the disabled button.
ButtonRenderer.DrawButton(myBuffer.Graphics, buttonArea, PushButtonState.Disabled);
// Draw the disabled button text.
var formattedValueString = FormattedValue as string;
if (formattedValueString != null)
{
TextRenderer.DrawText(myBuffer.Graphics, formattedValueString, DataGridView.Font, buttonArea, SystemColors.GrayText, TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}
myBuffer.Render();
}
}
else
{
// The button cell is enabled, so let the base class handle the painting.
base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
}
Вы можете использовать эту статью MSDN Статья MSDN: кнопка "Отключить" в dataGridView, она использует класс для кнопки "Просмотр данных" и заметить, что вам нужно проверять состояние включения кнопки всякий раз, когда вы хотите обработать ее
У меня есть две поправки к ответу @Chris Staley (и, следовательно, к ответу @Jay Riggs).
1: ЕслиSelectionMode
являетсяFullRowSelect
DataGridView вы можете добавить следующий код, чтобы отобразить выделение выбранной строки в ячейке кнопки:
// Draw the cell background, if specified.
if ((paintParts & DataGridViewPaintParts.Background) == DataGridViewPaintParts.Background)
{
var backColor = elementState.HasFlag(DataGridViewElementStates.Selected)
? cellStyle.SelectionBackColor
: cellStyle.BackColor;
using var cellBackground = new SolidBrush(backColor);
myBuffer.Graphics.FillRectangle(cellBackground, cellBounds);
}
2: Чтобы правильно определить границу, чтобы она соответствовала «обычной» ячейке кнопки (чтобы кнопка не заполняла всю ячейку), вы можете добавить следующий код:
// Calculate the area in which to draw the button.
var buttonArea = cellBounds;
var cellPadding = cellStyle.Padding;
var buttonAdjustment = BorderWidths(advancedBorderStyle);
buttonArea.X += cellPadding.Left + buttonAdjustment.Left;
buttonArea.Y += cellPadding.Top + buttonAdjustment.Top;
buttonArea.Width -= cellPadding.Horizontal + buttonAdjustment.Left + buttonAdjustment.Right;
buttonArea.Height -= cellPadding.Vertical + buttonAdjustment.Top + buttonAdjustment.Bottom;