+-
在C#中调整ComboBox下拉宽度
我有这段代码可以调整comboBox下拉菜单的宽度:

  private void comboBox_DropDown(object sender, EventArgs e)
  {
     ComboBox senderComboBox = (ComboBox)sender;
     int width = senderComboBox.DropDownWidth;
     Graphics g = senderComboBox.CreateGraphics();
     Font font = senderComboBox.Font;
     int vertScrollBarWidth =
         (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
         ? SystemInformation.VerticalScrollBarWidth : 0;
     int newWidth;

     foreach (string s in ((ComboBox)sender).Items)
     {
        newWidth = (int)g.MeasureString(s, font).Width
            + vertScrollBarWidth;

        if (width < newWidth)
        {
           width = newWidth;
        }
     }

     senderComboBox.DropDownWidth = width;
  }

它的效果很好,除了它可以将下拉菜单的宽度向右扩展,而我更希望将其向左扩展,因为comboBox位于表单的右侧.您可能有任何想法或建议.谢谢.

最佳答案
好的,.Anchor的工作方式不像我预期的那样,所以这是一个确实有效的全新答案,但是我觉得这是一种破解,(但也许这是一种管理它的完全合理的方式):

int x = 10;           
comboBox1.Location = new Point(comboBox1.Location.X - x, comboBox1.Location.Y);
comboBox1.Width += x; 

此代码将其沿x轴拉回10像素,然后将ComboBox1扩展10像素.

这对我来说非常顺利.这对您有用吗?

点击查看更多相关文章

转载注明原文:在C#中调整ComboBox下拉宽度 - 乐贴网