`

c#动态设置combobox控件下拉项宽度以实现下拉项文字可以完全显示[转]

    博客分类:
  • C#
阅读更多

这个几乎是来自这里的啊:
http://blog.csdn.net/ccy3253/archive/2008/01/26/2067304.aspx

在winform编程中,combox是我们经常用到的控件,往往因为界面排版或者其它原因,comboBox的宽度受到限制,而下拉列表中的内容太长。如果按照combobox的默认设置 ,下拉列表和comboBox的宽度一样,并不会跟随内容的变化而变化,这就造成下拉列表中有些项的内容太长而不能全部显示出来.

如果能够让下拉列表的宽度随着内容的变化而变化,这个问题不就解决了。下面我们看看如何让comboxBox的下拉列表宽度自适应内容的宽度,方法AdjustComboBoxDropDownListWidth()用来调整comboBox宽度,但是如果每次在我们向comboBox中添加一项后,就要调用一下这个方法,那就太麻烦了。能不能把这种自适应宽度的功能集成到comboBox中呢?可以,这里我们继承ComboBox,实现一个自定义的控件,在用户每次打开下拉列表的时候,让控件自动调整下拉列表的宽度。


0.控件类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
  public partial class CtrlComboBox :ComboBox
  {
    protected override void OnDropDown(EventArgs e)
         {
            base.OnDropDown(e);
            AdjustComboBoxDropDownListWidth();  //调整comboBox的下拉列表的大小
        }

        private void AdjustComboBoxDropDownListWidth()
         {
            Graphics g = null;
            Font font = null;
            try
             {
                int width = this.Width;
                g = this.CreateGraphics();
                font = this.Font;

                //checks if a scrollbar will be displayed.
                //If yes, then get its width to adjust the size of the drop down list.
                int vertScrollBarWidth =
                    (this.Items.Count > this.MaxDropDownItems)
                    ? SystemInformation.VerticalScrollBarWidth : 0;

                int newWidth;
                foreach (object s in this.Items)  //Loop through list items and check size of each items.
                 {
                    if (s != null)
                     {
                        //newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
                       newWidth = (int)g.MeasureString(((ComboBoxData)s).StrText, font).Width
                            + vertScrollBarWidth;
                        if (width < newWidth)
                            width = newWidth;   //set the width of the drop down list to the width of the largest item.
                    }
                }
                this.DropDownWidth = width;
            }
            catch
             { }
            finally
             {
                if (g != null)
                    g.Dispose();
            }
        }
  }
}




1.数据源类
public class ComboBoxData
  {
    private string _StrValue;
    private string _StrText;

    public ComboBoxData(string StrValue, String StrText)
    {
      _StrText = StrText;
      _StrValue = StrValue;

    }

    public string StrValue
    {
      get
      {
        return _StrValue;
      }
      set
      {
        _StrValue = value;
      }
    }

    public string StrText
    {
      get
      {
        return _StrText;
      }
      set
      {
        _StrText = value;
      }
    }


  }

2.form 里使用它。



ArrayList al = new ArrayList();
      for (int i = 0; i < 9; i++)
      {
        al.Add( new ComboBoxData("aaaaaaaaaaaaaaaaaaa" + i.ToString(), "aaaaaaaaaaaaaaaaaaa" + i.ToString()));
      }
      al.Add(new ComboBoxData("只要在我们向combox添加完所有项后,调用一下,就可以调整comboBox下拉列表的宽度了", "只要在我们向combox添

加完所有项后,调用一下,就可以调整comboBox下拉列表的宽度了"));
      ctrlComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
      ctrlComboBox1.DisplayMember = "StrText";
      ctrlComboBox1.ValueMember = "StrValue";
      ctrlComboBox1.DataSource = al;



如果想实现在选择了某项后,combobox以提示的方式来查看选择项的完全text,那要加一个toolTip

 private void comboBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
    {
      this.toolTip1.SetToolTip(this.comboBox1, this.comboBox1.Text);
    }

分享到:
评论
4 楼 hsl313 2018-08-10  
lameig 写道

		bolItemChanged = false;
	} catch (Exception e) {
		//Comm.Log(this, "调整下拉框宽度:M={0},S={1},T={2}", e.Message, e.Source, e.StackTrace);
	}



经过整理,通过以上代码能兼容字符串和任意类型的对象


bolItemChanged = false;
这个没有变量
3 楼 hsl313 2018-08-10  
原来是要登录才可以查看到啊
lameig 写道
	try {
		int vertScrollBarWidth = (this.Items.Count > this.MaxDropDownItems)
			? SystemInformation.VerticalScrollBarWidth : 0;
		int newWidth;
		//初始宽度等于控件宽度
		int width = this.Width;
		foreach (object item in this.Items) {
			if (item != null) {
				string text = item.ToString();
				if (item is string) {
					text = (string)item;
				} else if (!string.IsNullOrEmpty(this.DisplayMember)) {
					Type type = item.GetType();
					PropertyInfo prop = type.GetProperty(this.DisplayMember);
					if (prop != null) {
						text = (string)prop.GetValue(item, null);
					}
				}
				newWidth = TextRenderer.MeasureText(text, this.Font).Width + vertScrollBarWidth;
				if (width < newWidth)
					width = newWidth;
			}
		}
		this.DropDownWidth = width;
		bolItemChanged = false;
	} catch (Exception e) {
		//Comm.Log(this, "调整下拉框宽度:M={0},S={1},T={2}", e.Message, e.Source, e.StackTrace);
	}



经过整理,通过以上代码能兼容字符串和任意类型的对象

2 楼 lameig 2013-09-29  
	try {
		int vertScrollBarWidth = (this.Items.Count > this.MaxDropDownItems)
			? SystemInformation.VerticalScrollBarWidth : 0;
		int newWidth;
		//初始宽度等于控件宽度
		int width = this.Width;
		foreach (object item in this.Items) {
			if (item != null) {
				string text = item.ToString();
				if (item is string) {
					text = (string)item;
				} else if (!string.IsNullOrEmpty(this.DisplayMember)) {
					Type type = item.GetType();
					PropertyInfo prop = type.GetProperty(this.DisplayMember);
					if (prop != null) {
						text = (string)prop.GetValue(item, null);
					}
				}
				newWidth = TextRenderer.MeasureText(text, this.Font).Width + vertScrollBarWidth;
				if (width < newWidth)
					width = newWidth;
			}
		}
		this.DropDownWidth = width;
		bolItemChanged = false;
	} catch (Exception e) {
		//Comm.Log(this, "调整下拉框宽度:M={0},S={1},T={2}", e.Message, e.Source, e.StackTrace);
	}



经过整理,通过以上代码能兼容字符串和任意类型的对象
1 楼 lameig 2013-09-29  
谢谢分享,在使用中,我用到了多种对象,而不仅仅是一种类型,这样又该如何才能兼容呢?如果要把所有使用代码的地方都改成同一种类型的对象估计很难改,还麻烦请指点一下谢谢!

相关推荐

Global site tag (gtag.js) - Google Analytics