vb.net - Reusable function to adjust the width of combobox items to longest item in the list -
my intent able use function adjust width of drop down items included in drop down shown (length wise). i'm trying create function i'll able use multiple comboboxes. being called load cbo function, after data has been loaded not adjusting .dropdownwidth.
private sub adjustcombobox(byval comboboxname combobox) dim maxwidth = 0 dim temp = 0 each item object in comboboxname.items temp = textrenderer.measuretext(item.tostring(), comboboxname.font).width if temp > maxwidth maxwidth = temp end if next comboboxname.dropdownwidth = maxwidth end sub
edit:
comboboxload function
dim da new sqldataadapter(sql, objconnection) dim ds new dataset da.fill(ds, "prov") if ds.tables("prov").rows.count > 0 c .datasource = ds.tables("prov") .valuemember = "no" .displaymember = "name" .selectedindex = -1 end end if
first, use actual datasource
, not items. allows short solution:
private function getmaxdatasize(dt datatable, mem string) int32 dim longestitem = dt.asenumerable.select(function(q) q.field(of string)(mem)). orderby(function(z) z.length). last() ' assumes cbo's use same font dim longestsize = textrenderer.measuretext(longestitem, cboe.font) return longestsize.width + systeminformation.verticalscrollbarwidth + 5 end function
note method accounts verticalscrollbarwidth
, slight fudge factor account internal gutters, padding, margins etc. if different combos use different fonts, pass each method well. usage:
' "text" displaymember name / column name cboe.dropdownwidth = getmaxdatasize(dtlorem, "text")
using "lorem ipsum dolor" fragments, 1 long one, result:
Comments
Post a Comment