用datagrid控件显示表格数据,当表格内容过多时,datagrid控件单元格宽度并不足以用来完全显示表格中的数据内容。而只有自己每次去拉动分界线,来进行调整。当出现表格字段比较多时,这样做就显得很麻烦。 以下是用程序根据表格内容来自动调整datagrid控件单元格宽度。 先定义一个sub过程autosizecol,用来调整datagrid中的列宽。 如下: public sub autosizecol(byval col as integer) dim width as single width = 0 dim numrows as integer numrows = ctype(datagrid1.datasource, datatable).rows.count dim g as graphics g = graphics.fromhwnd(datagrid1.handle) dim sf as stringformat sf = new stringformat(stringformat.generictypographic) dim size as sizef dim i as integer i = 0
do while (i < numrows) size = g.measurestring(datagrid1(i, col).tostring, datagrid1.font, 500, sf) if (size.width > width) then width = size.width end if i = (i + 1) loop
现在就可以表格内容来定义整张表所有列的宽度了。如下: public sub autosizetable() dim numcols as integer numcols = ctype(datagrid1.datasource, datatable).columns.count dim i as integer i = 0 do while (i < numcols) autosizecol(i) i = (i + 1) loop end sub
只要使用以上两个sub过程就可以达到你想要的结果了!
一个完整的实例如下: private sub form1_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load dim connstring as string connstring = "provider=microsoft.jet.oledb.4.0;data source=northwind.mdb" dim sqlstring as string sqlstring = "select * from customers" dim dataadapter as oledbdataadapter dataadapter = nothing dim _dataset as dataset _dataset = nothing
try
dim connection as oledbconnection connection = new oledbconnection(connstring)
dataadapter = new oledbdataadapter(sqlstring, connection)
_dataset = new dataset dataadapter.fill(_dataset, "customers") connection.close() catch ex as exception messagebox.show("出错!") me.close() return end try dim tablestyle as datagridtablestyle tablestyle = new datagridtablestyle tablestyle.mappingname = "customers"
datagrid1.tablestyles.clear() datagrid1.tablestyles.add(tablestyle) datagrid1.datasource = _dataset.tables("customers") end sub
private sub button1_click(byval sender as system.object, byval e as system.eventargs) handles button1.click autosizetable() end sub
private sub button2_click(byval sender as system.object, byval e as system.eventargs) handles button2.click autosizecol(1) end sub