I have NumericeUpdown embedded inside an EditingListView column in a Windows desktop application. The ListView will show decimal value as text and when clicked, the NumericUpDown should be visible with the decimal value in it so that the user can edit it. But when the user clicks on the cell, the NumericUpDown control is showing with value “0.00”
// Inside Constructor
lvUpdates.SetEditableColumn(FinalizeAmountColumn, EditingListViewEditType.NumericUpDown);
// Event handlers
private void lvUpdates_ControlShowing(object sender, CancelEditingListViewEventArgs e)
{
var lvi = (PropertyListViewItem)lvUpdates.Items[e.Row];
if (lvi == null)
return;
var info = (DebtSetOffMatchUpdateInformation)lvi.Tag;
if (info.MatchAmount <= 0 || info.RecordType != DebtSetOffMatchUpdateInformation.RecordTypes.Finalize)
{
e.Cancel = true;
return;
}
if (e.Column == FinalizeAmountColumn && e.Control is NumericUpDown nud)
{
nud.Minimum = 0;
nud.Maximum = info.MatchAmount;
nud.DecimalPlaces = 2;
var sValue = lvi.SubItems[FinalizeAmountColumn].Text;
if (!sValue.HasValue())
sValue = "0.00";
nud.Value = decimal.Parse(sValue, NumberStyles.Any);
nud.Text = sValue;
nud.Refresh();
}
}
9
I finally resolved the problem by replacing the custom event handler with the MouseClick handler. For reference, I’m posting the solution in case anyone faces similar issues with custom controls and wants to explore other event handlers.
private void lvUpdates_MouseClick(object sender, MouseEventArgs e)
{
var hitTestInfo = lvUpdates.HitTest(e.X, e.Y);
var lvItem = hitTestInfo.Item;
var columnIndex = hitTestInfo.Item.SubItems.IndexOf(hitTestInfo.SubItem);
var info = (DebtSetOffMatchUpdateInformation)lvItem.Tag;
if (info.MatchAmount <= 0 || info.RecordType != DebtSetOffMatchUpdateInformation.RecordTypes.Finalize)
{
return;
}
if (columnIndex == FinalizeAmountColumn)
{
NumericUpDown nud = new NumericUpDown
{
Minimum = 0,
Maximum = info.CurrentBalance < info.MatchAmount ? info.CurrentBalance : info.MatchAmount,
DecimalPlaces = 2
};
if (decimal.TryParse(lvItem.SubItems[columnIndex].Text, NumberStyles.Any, CultureInfo.CurrentCulture, out var currentValue)) nud.Value = currentValue;
else nud.Value = 0.00M;
// Position and show the NumericUpDown control
nud.Bounds = hitTestInfo.SubItem.Bounds;
nud.Leave += (s, ev) =>
{
// When leaving the control, make sure we display the result in money format in ListView
var newAmount = nud.Value;
lvItem.SubItems[columnIndex].Text = newAmount == 0 ? string.Empty : Globals.FormatCurrency(newAmount);
lvUpdates.Controls.Remove(nud); // Remove the NumericUpDown control after editing
};
lvUpdates.Controls.Add(nud);
nud.Focus();
}
}