开发者

How to set DataGridView's Height properties if the control is inside a ToolStripControlHost? C# WINFORMS

开发者 https://www.devze.com 2023-01-16 02:25 出处:网络
I have a TextBox that will show a DataGridView within a contextMenuStrip everytime the user presses the F1key. I used ToolStripControlHost to host the dataGridView inside the contextMenuStrip. Please

I have a TextBox that will show a DataGridView within a contextMenuStrip everytime the user presses the F1 key. I used ToolStripControlHost to host the dataGridView inside the contextMenuStrip. Please consider my code:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.F1)
    {
        dataGridView1.BindingContext = this.BindingContext;
        dataGridview1.Height = 30;
        dataGridView1.DataSource = dt; // some DataTable with 50+ rows,..or greater.

        ToolStripControlHost tsHost = new ToolStripControlHost(dataGridView1);
        contextMenuStrip1.Items.Clear();
        contextMenuStrip1.Items.Add(tsHost);

        contextMenuStrip1.Show(textBox1, 0, 27);
    }
}

My problem is I can't set programmatically the height of the dataGridView when it's already开发者_开发技巧 added in the contextMenuStrip as an item. Since I can't set the height of the grid, the tendency is it adjusts its height depending on the size of its dataSource.

I'm missing something in my code? Please help.. thanks.


You can't change height of your dataGridView1 directly because it's inside other controls - therefore it's height is limited by the size of it's parent controls. If you want to change it's height, you should instead change the heights of contextMenuStrip1 and tsHost. I prefer doing it like this:

dataGridView1.Dock = DockStyle.Fill;
tsHost.Dock = DockStyle.Fill;
contextMenuStrip1.Height = 30;

If it doesn't work, try finding contextMenuStrip1's parent controls and change their heights.


I already figured it out. I just added this code:

ToolStripControlHost tsHost = new ToolStripControlHost(dataGridView1);
tsHost.AutoSize = false; // Set AutoSize property to false.
tsHost.Height = 30;      // then set Height property value.
contextMenuStrip1.Items.Clear();
contextMenuStrip1.Items.Add(tsHost);
0

精彩评论

暂无评论...
验证码 换一张
取 消