Repositioning Winform label in code, not working as expected
-
I have a windows forms application with a single form. On the form I have a
ListView
control inDetails
mode that I am using as a grid to display data; the ListView'sAnchor
property is set to all 4 edges (Top, Bottom, Left, Right), so it will retain it's distance to all edges when resized. The data is readonly, no changes will be made to it. The ListView has 4 columns, one of which is a dollar amount and I decided to put aLabel
control beneath theListView
control aligned with the amount column. In code, I set the label'sText
to be the total of the amounts from the ListView's amount column; the label has no anchoring or docking andAutoSize
is turned off. I decided that since theListView
columns can be resized and also theListView
itself can change size if the form is maximized or restored, then I'd like to move the label around so that it stays aligned with the amount column in the ListView. The ListView is namedlstInvoices
and the label is namedlblTotalAmount
. I hooked up the ListView'sColumnWidthChanged
event handler like so:private void lstInvoices\_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) { int columnIndex = lstInvoices.Columns.IndexOfKey(NETAMOUNT\_COLUMN\_NAME); if (columnIndex != -1 && (columnIndex == e.ColumnIndex) || (e.ColumnIndex == columnIndex - 1)) AlignTotalLabelWithAmountColumn(); }
and here's the AlignTotalLabelWithAmountColumn function:
private void AlignTotalLabelWithAmountColumn() { int columnIndex = lstInvoices.Columns.IndexOfKey(NETAMOUNT\_COLUMN\_NAME); if (columnIndex == -1) return; lblTotalAmount.Width = lstInvoices.Columns\[columnIndex\].Width; lblTotalAmount.Left = lstInvoices.Left; for (int i = 0; i < columnIndex; i++) { lblTotalAmount.Left += lstInvoices.Columns\[i\].Width; } lblTotalAmount.Top = lstInvoices.Bottom + 2; }
In the function, I set the label's
Width
property to the same as the column in theListView
, and I calculate theLeft
position of the label by taking theLeft
of the ListView, plus theWidth
of each column up to the column I wish to line it up with. Last