簡體   English   中英

C#NET WinForms DataGridView的替代品,用於顯示用戶控件

[英]C# NET WinForms Alternative to DataGridView for displaying user controls

我正在編寫一個C#.NET WinForms應用程序,其中必須創建一個用戶控件的新實例,該實例將包含多個控件(TextBox,Button,CheckBox等)。 用戶控件必須一次創建一個並堆疊(垂直排列)。

我嘗試過的選項:

FlowLayoutPanel沒有索引值,我可以用來跟蹤當用戶單擊“添加新項”按鈕時將添加的許多用戶控件。

DataGridView沒有可容納用戶控件的列類型。 盡管DataGridView的功能與我所需的功能非常接近,但是我沒有找到任何代碼來添加UserControl類型的列。

有任何想法嗎?

也許TableLayoutPanel是您所需要的。

    protected override void OnLoad( EventArgs e )
    {
        var tableLayoutPanel = new TableLayoutPanel
        {
            Dock = DockStyle.Fill,
            AutoScroll = true
        };

        Controls.Add( tableLayoutPanel );

        // To reset row and columns use this

        // Reset row count and styles
        tableLayoutPanel.RowCount = 0;
        tableLayoutPanel.RowStyles.Clear();

        // Reset columns count and styles
        tableLayoutPanel.ColumnCount = 0;
        tableLayoutPanel.ColumnStyles.Clear();

        // For horizontal alignment we need add empty columns to fill space
        // |___emty fill___|Realcoulmn|___empty fill___|
        tableLayoutPanel.ColumnCount = 3;
        tableLayoutPanel.ColumnStyles.Add( new ColumnStyle( SizeType.Percent, 100 ) );  // Fill space
        tableLayoutPanel.ColumnStyles.Add( new ColumnStyle( SizeType.AutoSize ) );      // Real column with controls
        tableLayoutPanel.ColumnStyles.Add( new ColumnStyle( SizeType.Percent, 100 ) );  // Fill space

        tableLayoutPanel.SuspendLayout();

        for ( var i = 0; i < 5; i++ )
        {
            AddControl( tableLayoutPanel, 1 );
        }

        tableLayoutPanel.ResumeLayout( true );
    }

    public void IterateOverControls( TableLayoutPanel table )
    {
        // Iterate over all rows
        for ( var i = 0; i < table.RowCount; i++ )
        {
            var control = table.GetControlFromPosition( 1, i ); // Column 1
        }
    }

    public void AddControl( TableLayoutPanel tableLayoutPanel, int column )
    {
        var btn = new Button { Text = "Hello vertical stack!" };
        btn.Click += button_Click;

        // Add row to tableLayoutPanel and set it style
        tableLayoutPanel.RowCount++;
        tableLayoutPanel.RowStyles.Add( new RowStyle( SizeType.Absolute, btn.Height + 5 ) );

        // Add control to stack
        tableLayoutPanel.Controls.Add( btn, column, tableLayoutPanel.RowCount - 1 );
    }

    private void button_Click( object sender, EventArgs e )
    {
        var btnControl = sender as Control;
        if ( btnControl == null )
            return;

        var tableLayoutPanel = btnControl.Parent as TableLayoutPanel;
        if ( tableLayoutPanel == null )
            return;

        AddControl( tableLayoutPanel, 1 );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM