简体   繁体   中英

How can I make nullable string and datetime value in C#

ScdDept = fields[8] is DBNull? null:fields[8].ToString();
LeaveDate = fields[9] is DBNulL?DateTime.MaxValue:DateTime.Parse(fields[9].ToString());

I have A table and B table if I add some value to A table and I run my application same value added B table. But in A table LeaveDate and ScdDept is empty it looks "NULL" but B table if LeaveDate is empty it looks maksvalue and ScdDept is empty it looks empty. How can I solve this problem?

Your question is not clear. May be maksvalue of your question is MaxValue .

By your comment and question update I think instead of DateTime.MaxValue of LeaveDate Column you want null value.

Your LeaveDate property should look like

public DateTime? LeaveDate { get; set; }

and then you implement like this.

ScdDept = fields[8] is DBNull ? null : fields[8].ToString();
LeaveDate = fields[9] is DBNull ?  (DateTime?)null : DateTime.Parse(fields[9].ToString());

Approach 1: This will set default value if data is not parsing. It even returns whether parsing is done or not.

  String.TryParse( fields[8],out ScdDept );
  DateTime.TryParse(field[9],out LeaveDate );

Approach 2: While declaring ScdDept make it as a nullable

private string? ScdDept ;
private DateTime? LeaveDate ;

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