본문으로 바로가기

c# Combobox dropdownlist 넓이 자동으로 설정해주기

category 프로그래밍/.NET C# 2016. 6. 30. 14:01

 

 

c#코드

 void comboFileName_DropDown(object sender, EventArgs e)
        {
            ComboBox combo = sender as ComboBox;
            if (combo == null) { return; }

            int pw = GetLargestTextExtent(combo);  // 아이템 중에 가장 긴 글자의 넓이를 가져온다.
            if (pw != -1)
            {
                if (combo.Width > combo.DropDownWidth) // 만약에 원래 콤보박스 넓이가 더 넓다면 DropDownWidth를 콤보박스 Width를 준다.
                {
                    combo.DropDownWidth = combo.Width;
                }
                else { combo.DropDownWidth = pw; }  // 글자 넓이가 더 컸다면 글자 넓이를 DropDownWidth에 넣어준다.
            }
        }

 

       /// 제일 긴 글자 길이를 가진 아이템의 길이를 가져오는 메서드

        private int GetLargestTextExtent(System.Windows.Forms.ComboBox cbo)
        {
            int maxLen = -1;
            if (cbo.Items.Count >= 1)
            {
                using (Graphics g = cbo.CreateGraphics())
                {
                    int vertScrollBarWidth = 0;
                    if (cbo.Items.Count > cbo.MaxDropDownItems)
                    {
                        vertScrollBarWidth = SystemInformation.VerticalScrollBarWidth;
                    }
                    for (int nLoopCnt = 0; nLoopCnt < cbo.Items.Count; nLoopCnt++)
                    {
                        int newWidth = (int)g.MeasureString(cbo.Items[nLoopCnt].ToString(), cbo.Font).Width + vertScrollBarWidth;
                        if (newWidth > maxLen)
                        {
                            maxLen = newWidth;
                        }
                    }
                }
            }
            return maxLen;
        }