Bitterblue
Bitterblue

Reputation: 14075

C# - How to GET actual height of ComboBox

I know ComboBox.Height cannot be set easily. Can be changed with the Font. But I need to know it's final height. It doesn't update before the window and controls are displayed.

How can I calculate it ? When I run this the button is not below but behind the combo box:

// my forms must be disigned by code only (no designer is used)
public class Form1: Form
{
    public Form1()
    {
        ComboBox box = new ComboBox();
        box.Font = new Font("Comic Sans MS", 100, FontStyle.Regular);
        Controls.Add(box);

        Button button = new Button();
        button.Text = "hello world";
        button.SetBounds(box.Left, box.Bottom, 256, 32);
        button.SetBounds(box.Left, box.Height, 256, 32); // doesn't work either
        Controls.Add(button);
    }
}

Upvotes: 0

Views: 447

Answers (1)

User 12345678
User 12345678

Reputation: 7804

The problem is that the ComboBox.Bottom property will not be updated to compensate for the font size until the ComboBox has been drawn.

The solution is to dynamically add your controls in the Form.Load event instead of the constructor:

private void MainForm_Load(object sender, EventArgs e)
{
    ComboBox box = new ComboBox();
    box.Font = new Font("Comic Sans MS", 100, FontStyle.Regular);
    Controls.Add(box);

    Button button = new Button();
    button.Text = "hello world";
    button.SetBounds(box.Left, box.Bottom, 256, 32); 
    Controls.Add(button);
}

Upvotes: 1

Related Questions