简体   繁体   中英

C# datagridview set databound column value to a chosen default one

I have a DataGridView bound to a list of custom objects. A column is bound to a double datatype, and when I try to empty its content (to null), it throws a data error indicating DbNull cannot be converted into Double. What I'd like to accomplish is when a user enters a null value for the databound column, I'd like to set it to a default generic value, say 3.0.

I can handle dataerror and replace the value there, but this seems like a hackish solution. What is the recommended way of handling this?

Edit:

Here's my data class. The double datatype mentioned above is USL.

public class SPCModelDTO
{
        public string ProcessName { get; set; }
        public string CustomerName { get; set; }
        public string ModelName { get; set; }
        public double USL { get; set; }
}

Here's my code for databinding

dgvModel.DataSource = new BindingList<SPCModelDTO>(modelList);

Matching property name is declared in designer w/ respect to the dataclass properties.

As a side note, I cannot change USL's datatype to a nullable double .

Create a ViewModel which will be bound to the DataGrdiView .
In the ViewModel you can wrap USL in the nullable type

public class SPCModelDTOViewModel: INotifyPropertyChanged
{
    private SPCModelDTO _Model;
    public double? USL 
    { 
        get { return _Model.USL;} 
        set 
        {
            if(value.HasValue == false)
                _Model.USL = 3.0;
            else
                _Model.USL = value;
            this.RaisePropertyChangedEvent();
        } 
    }
    //Other model's properties
}

Line this.RaisePropertyChangedEvent(); will notify View(DataGridView) about changes and empty(null) value will be changed to default one
Of course your ViewModel class must implement INotifyPropertyChanged
How to: Implement the INotifyPropertyChanged Interface

for a databound column you can set DataSourceNullValue in DatagridViewColumn.DefaultCellStyle

dgvModel.DataSource = data;
var col = dgvModel.Columns["USL"];
col.DefaultCellStyle.DataSourceNullValue = 3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM