我有一个TableLayoutPanel,它包含多行,其中一些包含TextBox'es,其中一些包含DataGridView。我将包含DataGridView的TableLayoutPanel行的SizeType设置为AutoSize。我希望在DataGridView中添加/删除行时,包含它们的行的高度会增加/减少。它没有发生。我误解了这应该如何运作?有没有办法让我按照我期望的方式工作?
答案 0 :(得分:0)
这两位评论者是对的:)事实证明问题出在DataGridView本身。我最终使用了method 1。我构建了一个带有多个选项卡的测试应用程序,每个选项卡包含一个datagridview和一个用于添加行的按钮,以及一个用于删除行的按钮。第一个标签只包含这3个组件,我只是想确保它确实可以增长。在第二个选项卡中,我将3个组件放在Panel中,Autoscroll设置为true;这也很好。依此类推,直到我将datagridview和按钮放在一个用户控件内的TableLayoutPanel(也将Autoscroll设置为true)中。一切正常。为了防止其他人想要进行实验,只需在每个选项卡上删除2个按钮和数据网格视图,并使用以下代码(在主窗体中)初始化它们(而不是使用设计器)。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Setup(dataGridView1, buttonAddRow1, buttonRemoveRow1);
Setup(dataGridView2, buttonAddRow2, buttonRemoveRow2);
Setup(dataGridView3, buttonAddRow3, buttonRemoveRow3);
Setup(dataGridView4, button1, button2);
Setup(userControl11.dataGridView4, userControl11.button1, userControl11.button2);
dataGridView3.MaximumSize = new Size(0, 100);
dataGridView4.MaximumSize = new Size(0, 100);
}
#region static helpers
private static void Setup(DataGridView grid, Button buttonAdd, Button buttonRemove)
{
BindingList<RowItem> list = new BindingList<RowItem>();
SetupGrid(grid, list);
buttonAdd.Click += (sender, e) => Add(list);
buttonRemove.Click += (sender, e) => Remove(list);
}
private static void Add(BindingList<RowItem> list)
{
list.Add(new RowItem() { Name = "Row " + list.Count });
}
private static void Remove(BindingList<RowItem> list)
{
if (list.Count > 0)
list.RemoveAt(list.Count - 1);
}
private static void SetupGrid(DataGridView grid, BindingList<RowItem> list)
{
grid.AutoGenerateColumns = false;
grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
grid.RowHeadersVisible = false;
grid.Columns.Add(CreateTextColumn("Name"));
grid.DataSource = list;
}
/// <summary>
/// Sets read-only to true
/// </summary>
/// <param name="dataPropertyName"></param>
/// <param name="format"></param>
/// <param name="columnName"></param>
/// <returns></returns>
static public DataGridViewTextBoxColumn CreateTextColumn(string dataPropertyName, string columnName = null, string format = null, bool readOnly = true, DataGridViewAutoSizeColumnMode autosizeMode = DataGridViewAutoSizeColumnMode.AllCells, int width = 40, DataGridViewColumnSortMode sortMode = DataGridViewColumnSortMode.Automatic)
{
DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn();
textColumn.DataPropertyName = dataPropertyName;
textColumn.Name = String.IsNullOrEmpty(columnName) ? dataPropertyName : columnName;
textColumn.ReadOnly = readOnly;
textColumn.AutoSizeMode = autosizeMode;
textColumn.Resizable = DataGridViewTriState.True;
textColumn.Width = width;
if (!String.IsNullOrEmpty(format))
textColumn.DefaultCellStyle.Format = format;
textColumn.SortMode = sortMode;
return textColumn;
}
#endregion static helpers
}
class RowItem
{
public string Name { get; set; }
}