Силовая посадка столбца flexgrid

Как лучше всего принудительно подогнать столбцы msflexgrid в vb6?
чтобы все столбцы были видны и занимали максимальную ширину сетки!


Я пробовал этот код, но он не соответствует последнему столбцу внутри сетки, может ли кто-нибудь подсказать, в чем может быть проблема?

Public Sub **FlexGrid_AutoSizeColumns (** ByRef pGrid As MSHFlexGrid, _  
                                ByRef pForm As Form, _  
                                Optional ByVal pIncludeHeaderRows As Boolean = True, _  
                                Optional ByVal pAllowShrink As Boolean = True, _  
                                Optional ByVal pMinCol As Long = 0, _  
                                Optional ByVal pMaxCol As Long = -1, _  
                                Optional ByVal pBorderSize As Long = 8, _  
Optional fitToScreen As Boolean = False **)**  

Dim lngMinCol As Long, lngMaxCol As Long, lngCurrRow As Long  
Dim lngMinRow As Long, lngMaxRow As Long, lngCurrCol As Long  
Dim lngMaxWidth As Long, lngCurrWidth As Long  
Dim fntFormFont As StdFont  
Dim totalWidth As Integer  
totalWidth = 0  

Set fntFormFont = New StdFont  
Call CopyFont(pForm.Font, fntFormFont)  

Call CopyFont(pGrid.Font, pForm.Font)  

    With pGrid  
        lngMinCol = pMinCol  
        lngMaxCol = IIf(pMaxCol = -1, .Cols - 1, pMaxCol)  
        lngMinRow = IIf(pIncludeHeaderRows, 0, .FixedRows)  
        lngMaxRow = .Rows - 1  

        For lngCurrCol = lngMinCol To lngMaxCol  
            lngMaxWidth = IIf(pAllowShrink, 0, pForm.ScaleX(.ColWidth(lngCurrCol), vbTwips, pForm.ScaleMode))  

            For lngCurrRow = lngMinRow To lngMaxRow   '..find widest text (in scalemode of the form)
                lngCurrWidth = pForm.TextWidth(Trim(.TextMatrix(lngCurrRow, lngCurrCol)))
                If lngMaxWidth < lngCurrWidth Then lngMaxWidth = lngCurrWidth
            Next lngCurrRow

           lngMaxWidth = pForm.ScaleX(lngMaxWidth, pForm.ScaleMode, vbTwips)
           .ColWidth(lngCurrCol) = lngMaxWidth + (pBorderSize * Screen.TwipsPerPixelX)
           totalWidth = .ColWidth(lngCurrCol) + totalWidth

       Next lngCurrCol
   End With

Call CopyFont(fntFormFont, pForm.Font)

    If fitToScreen = True Then
        Dim i As Integer
        Dim gridWidth As Long
        gridWidth = pGrid.Width
        For i = 0 To pGrid.Cols - 1
            pGrid.ColWidth(i) = Int(gridWidth * pGrid.ColWidth(i) / totalWidth)
        Next
    End If  

Конец сабвуфера


person Vinay Kharecha    schedule 21.01.2013    source источник
comment
Можете ли вы показать изображение вашего текущего msflexgrid? Вы пробовали что-нибудь до сих пор?   -  person bonCodigo    schedule 21.01.2013


Ответы (2)


Один из способов, который я мог бы придумать, - это изменить размер ваших столбцов (с видимостью), чтобы они соответствовали максимальной ширине, найденной в столбце (текст). Функция возвращает либо 0, либо двойное значение. Пока возвращаемая максимальная ширина столбца не равна нулю, мы можем соответствующим образом настроить текущую ширину столбца сетки. Если ноль, то остается прежним.

Dim i, j,  as Integer
Dim maxWidth as Double
For i = 0 to MsFlexGrid1.Rows - 1
      For j = 0 to MsFlexGrid1.Cols - 1
             maxWidth = maxColWidth(j)
             If maxWidth > 0 then
                MsFlexGrid.ColWidth(j) = maxWidth
             End If
      Next j
Next i


Private Function maxColWidth(coNum as Integer) as Double
Dim i, Max as Integer
Max = 0
    With MsFlexGrid1
         For i = .FixedRows to .Rows-1
              If TextWidth(.TextMatrix(i, colNum)) > Max Then
                   Max = TextWidth(.TextMatrix(i, colNum))
              End If
         Next i    
         maxColWidth = Max
    End With
End Function
person bonCodigo    schedule 21.01.2013
comment
@ Винай, я хотел бы добавить сюда одну вещь: вы можете сделать дополнительную проверку. если выбранный вами max Width меньше максимальной ширины столбца, вы можете следовать максимальной ширине столбца, иначе вы установите ширину столбца равной выбранной максимальной ширине ? звучит отлично? :) - person bonCodigo; 22.01.2013

чтобы распределить оставшееся пространство по колонкам, разделите его на количество колонок и прибавьте к каждой колонке

'1 form with :
'    1 msflexgrid : name=MSFlexGrid1
Option Explicit

Private Sub Form_Load()
  Dim intCol As Integer
  'example form and grid configuration
  Move 0, 0, 10000, 5000
  With MSFlexGrid1
    .FixedRows = 0
    .FixedCols = 0
    .Rows = 10
    .Cols = 10
    For intCol = 0 To .Cols - 1
      .ColWidth(intCol) = (intCol + 1) * 107
    Next intCol
  End With 'MSFlexGrid1
End Sub

Private Sub Form_Resize()
  MSFlexGrid1.Move 0, 0, ScaleWidth, ScaleHeight
End Sub

Private Sub MSFlexGrid1_Click()
  DistributeWidth
End Sub

Private Sub DistributeWidth()
  Dim intCol As Integer, intColSel As Integer
  Dim lngWidth As Long
  Dim lngRemaining As Long
  Dim lngExpand As Long
  With MSFlexGrid1
    intColSel = .Col                                          'remember selected column
    .Col = 0                                                  'select first column to ...
    lngWidth = .Width - .CellLeft * 2                         '... take flexgrid-borders into account
    .Col = intColSel                                          'select column again
    lngRemaining = lngWidth - InUse                           'calculate the remaining space
    If lngRemaining > 0 Then
      lngExpand = lngRemaining \ .Cols                        'distribute the remaining space over the columns
      For intCol = 0 To .Cols - 1
        .ColWidth(intCol) = .ColWidth(intCol) + lngExpand
      Next intCol
      lngExpand = lngRemaining Mod .Cols
      .ColWidth(.Cols - 1) = .ColWidth(.Cols - 1) + lngExpand 'since we are working with longs, apply the remaining fraction to the last column
    Else
      'what to do with lack of space? Shrink columns or expand grid or nothing?
    End If
  End With 'MSFlexGrid1
End Sub

Private Function InUse() As Long
'calculate how much of the gridwidth is already in use by the columns
  Dim intCol As Integer
  Dim lngInUse As Long
  With MSFlexGrid1
    lngInUse = 0
    For intCol = 0 To .Cols - 1
      lngInUse = lngInUse + .ColWidth(intCol)
    Next intCol
  End With 'MSFlexGrid1
  InUse = lngInUse
End Function

Приведенный выше пример почему-то не всегда полностью заполняет область, хотя я думаю, что логика верна, и я не вижу ничего упущенного...

Я думаю, это дает аналогичный результат тому, что у вас есть? или немного лучше?

person Hrqls    schedule 22.01.2013