dotnet / dotnet/winforms

Databinding for an invisble NumericUpDown , may cause ArgumentOutOfRangeException

Open
#13,470 3 comments 0 reactions 1 assignee Claimed by @KlausLoeffelmann View on GitHub
area-Binding area-System.Drawing priority-3
Dominant language
C#
Stars
4.9k
Forks
1.1k
Avg merge
20h 23m
Merged PRs (30d)
103

Description

### .NET version

8.0
It affects netfx-2.0, 3.5 ,4.0, 4.6, 4.8, and net-8.0 which I have tested.

### Did it work in .NET Framework?

No

### Did it work in any of the earlier releases of .NET Core or .NET 5+?

Not tested.

### Issue description

Control databinding bugs.

### Steps to reproduce

Run the code, change value of the NumericUpDown in tabPage1, you will got:
```
System.ArgumentOutOfRangeException:““0” is invalid for “Value”. “Value” should be between 'Minimum' and 'Maximum'. (Parameter 'value') Actual value was 0.”
```
If you first switch to tabPage2, and then switch back to tabPage1, change value of the NumericUpDown , no exception occurs.

```C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace WinFormsApp2
{
class Data : INotifyPropertyChanged
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

bool SetValue(ref T field, T value, string name)
{
if (!object.Equals(field, value))
{
field = value;
RaisePropertyChanged(name);
return true;
}
return false;
}
#endregion

public int _TestInt = 42;
public int TestInt
{
get => _TestInt;
set => SetValue(ref _TestInt, value, nameof(TestInt));
}

public int _TestInt2 = 18;
public int TestInt2
{
get => _TestInt2;
set => SetValue(ref _TestInt2, value, nameof(TestInt2));
}
}
internal static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

var data = new Data();

var form = new Form();
form.Size = new System.Drawing.Size(200, 160);

var tabControl1 = new TabControl();
tabControl1.Dock = DockStyle.Fill;
form.Controls.Add(tabControl1);

var tabPage1 = new TabPage();
tabPage1.Text = "tabPage1";
tabControl1.TabPages.Add(tabPage1);

var num1 = new NumericUpDown();
num1.DataBindings.Add(nameof(num1.Value), data, nameof(data.TestInt), false, DataSourceUpdateMode.OnPropertyChanged);
tabPage1.Controls.Add(num1);

var tabPage2 = new TabPage();
tabPage2.Text = "tabPage2";
tabControl1.TabPages.Add(tabPage2);

var num2 = new NumericUpDown();
num2.Minimum = 8;
num2.DataBindings.Add(nameof(num2.Value), data, nameof(data.TestInt2), false, DataSourceUpdateMode.OnPropertyChanged);
tabPage2.Controls.Add(num2);

Application.Run(form);
}
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.