我正在嘗試在 Winforms 中禁用 DataGridView 中的行選擇。我使用了下面的代碼,它按預期作業,而不是第一行。
protected override void OnRowValidating(DataGridViewCellCancelEventArgs e)
{
e.Cancel = true;
}
對于第一行,此方法未呼叫,我可以選擇該行。任何人都可以解決這個問題
我想禁用所有型別的選擇(行、列或單元格選擇)。我不能使用IsEnabled = false,因為需要保留水平/垂直滾動。
uj5u.com熱心網友回復:
我想禁用所有型別的選擇(行、列或單元格選擇)。我不能使用
Enabled = false,因為需要保留水平/垂直滾動。
要完全禁用 DataGridView 中的任何選擇,您可以設定CurrentCell = null用戶何時更改 Row 或 Cell,與 Control 互動。
這當然也會禁用對單元格的任何編輯。
這就像強制只讀模式;默認ReadOnly屬性不會阻止可見的選擇。
網格可以滾動,也可以單擊列的標題允許對資料進行排序。
設定CurrentCell = null會阻止所有選擇,但拖動滑鼠指標時會突出顯示行。
僅當MultiSelect = true設定為時false,無法通過拖動滑鼠進行選擇時才會發生這種情況。
建議編輯 1(不允許選擇、不允許編輯、允許排序):
- 添加了一個
SelectionEnabled公共(根據需要修改)屬性,以便您可以切換此狀態。 OnSelectionChanged被覆寫以應用狀態(您必須base在 set 之前呼叫CurrentCell = null)。
public class DataGridViewEx : DataGridView {
private bool m_SelectionEnabled = true;
private bool multiSelectCachedState = false;
public DataGridViewEx() { }
public bool SelectionEnabled {
get => m_SelectionEnabled;
set {
if (m_SelectionEnabled != value) {
m_SelectionEnabled = value;
if (!m_SelectionEnabled) {
multiSelectCachedState = MultiSelect;
MultiSelect = false;
ClearSelection();
}
else {
MultiSelect = multiSelectCachedState;
}
}
}
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
multiSelectCachedState = MultiSelect;
}
protected override void OnSelectionChanged(EventArgs e)
{
base.OnSelectionChanged(e);
// Prevents Cell edit
if (!m_SelectionEnabled) CurrentCell = null;
}
}
建議編輯 2(不允許選擇,允許單元格編輯,允許排序):
As you can see in the .Net Source Code about CurrentCell, setting this property to null causes a call to ClearSelection(), but based on some conditions.
Calling ClearSelection() directly, causes a call to SetSelectedCellCore() (suspends bulk paint, clears the selection and invalidates Columns and Rows in the end), which doesn't prevent editing.
The code is, give or take, the same:
public bool SelectionEnabled {
get => m_SelectionEnabled;
set {
if (m_SelectionEnabled != value) {
m_SelectionEnabled = value;
if (!m_SelectionEnabled) ClearSelection();
}
}
}
protected override void OnSelectionChanged(EventArgs e)
{
base.OnSelectionChanged(e);
// Does not prevent Cell edit
if (!m_SelectionEnabled) ClearSelection();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/450351.html
