【问题标题】:pass the value null when datetime is not filled by user当用户未填写日期时间时传递值 null
【发布时间】:2014-01-30 10:20:27
【问题描述】:

我创建了一个函数。用户可以在哪里选择日期。而当用户没有选择我想要传递的日期时 null 。

 public DataSet  GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime  startDate, DateTime  endDate, string invoiceNumber, ref int totalInvoice)
{
 // doing something here 
}

这是我调用函数的代码部分

_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize, clientid, Convert.ToDateTime(txtFirstDate.Text.Trim()), Convert.ToDateTime(txtLastDate.Text.Trim()), txtInvoiceNumber.Text.Trim(), ref invoicecount);

有时用户无法填写txtFirstDate.Text,但我正在转换 Convert.TodateTime() 所以我该如何解决这个问题,因为当用户不填写日期时间时它会给我异常。那么我该如何处理呢。

【问题讨论】:

  • 使日期时间可以为空.. 并检查值是否为空
  • 如果值为空,那么我如何发送我收到异常的值。因为当用户没有在文本框上填写任何内容时,这将如何转换。TodateTime()
  • 向 DAC 函数 GetInvoicebyPaging() 发送值,其中两个值是 DateTime startDate,DateTime endDate,
  • @zaki 或者我需要使用 DateTime.Tryparse() 如果这样我如何在我的函数中使用 DateTime.Tryparse()

标签: asp.net c#-4.0


【解决方案1】:

您需要将方法更改为:

public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime?  startDate, DateTime  endDate, string invoiceNumber, ref int totalInvoice)
{
    // doing something here 
}

当你解析用户数据时,你可以这样做:

DateTime? start = null;
DateTime possibleStartValue;
if(!string.IsNullOrEmpty(txtTextBox.Text) && DateTime.TryParse(txtTextBox.Text, out possibleStartValue))
{
    start = possibleStartValue;
}

【讨论】:

    【解决方案2】:

    您可以按如下方式创建一个可为空的日期时间变量

    DateTime? value = null;
    

    并作为参数传递

    在您的函数中,您可以使用 DateTime? value 作为参数

    所以你必须执行以下步骤

     DateTime? startDate=txtFirstDate.Text.Trim()==""?null:Convert.ToDateTime(txtFirstDate.Text.Trim());
    

    更改您的函数参数,使其可以像上面一样采用空值。

    【讨论】:

      【解决方案3】:

      对于您希望能够接受为空的任何日期,例如DateTime startDate,您需要使它们可以为空,例如DateTime? startDate

      然后在您致电GetInvoicebyPaging 之前尝试整理日期时间。

      DateTime startDate;
      var correctStart = DateTime.TryParse(txtFirstDate.Text.Trim(), out startDate);
      

      然后像传递参数一样

      _orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize, 
      clientid, (correctStart ? startDate : null), etc
      

      您可能还需要检查txtFirstDate.Text 是否为空。 在上面声明startDate 之后,你可以这样做:

      var dateString = txtFirstDate.Text ?? "";
      

      并将dateString.Trim() 传递给DateTime.TryParse

      【讨论】:

        猜你喜欢
        • 2018-02-27
        • 2015-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多