如何让DataGridView在编辑时显示多行文本? 我补充道:
dataGridView1.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
编辑完成后才显示多行。
这是在测试中对我有用的一种方法。通常,当编辑控件中的文本发生变化时,基础单元格值不会发生变化。该值在提交时被复制,取消操作只会跳过复制操作。
但是,通过更改基础单元格值以响应编辑器控件中的更改,则行高会因
AutoSizeRows
设置而跟踪。但是,如果编辑被取消(例如,按下 [Escape] 键),现在我们有责任使用显示编辑器时推送的 _revertText
值来恢复单元格值。
DefaultCellStyle.WrapMode
设置为 DataGridViewTriState.True
AutoSizeRowsMode
设置为 DataGridViewAutoSizeRowsMode.AllCells
public partial class MainForm : Form
{
public MainForm() => InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
dataGridView.DataSource = Records;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.Columns[nameof(Record.Description)].Width = 150;
dataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
dataGridView.CellValidating += (sender, e) =>
{
Debug.WriteLine(
$"Ensure that only one cell validation per commit {dataGridView.CurrentCell?.Value}");
};
dataGridView.EditingControlShowing += (sender, e) =>
{
if (e.Control is TextBox textBox)
{
_revertText = textBox.Text;
textBox.TextChanged -= localOnTextChanged;
textBox.PreviewKeyDown -= localPreviewKeyDown;
textBox.TextChanged += localOnTextChanged;
textBox.PreviewKeyDown += localPreviewKeyDown;
void localOnTextChanged(object? sender, EventArgs e)
{
BeginInvoke(() =>
{
dataGridView.CurrentCell.Value = textBox.Text;
});
}
void localPreviewKeyDown(object? sender, PreviewKeyDownEventArgs e)
{
if(e.KeyData == Keys.Escape)
{
dataGridView.CurrentCell.Value = _revertText;
}
}
}
};
Records.Add(new Record());
}
string _revertText = string.Empty;
BindingList<Record> Records = new BindingList<Record>();
}
class Record
{
public string? Description { get; set; }
}