1

我有以下表格:

在此处输入图像描述


一旦我点击按钮它的工作方式是这样的,以上所有参数都传递给GetData方法

protected void btnShow_Click(object Sender, EventArgs e)
{
     ShowReport();
}
private void ShowReport()
{
     //Reset
     ReportViewer1.Reset();

      //DataSource
      DataTable dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, DateTime.Parse(date.Text));
            ............................
}

这是GetData方法

private DataTable GetData(string type, string category, string country, string subsidary, string dateHERE)
{
    // date = date.Value.ToOADate();

    DateTime? mydate = null;
    DateTime date2;
    bool check = DateTime.TryParse(dateHERE, out date2);
    if (check)
    {
        mydate = date2;
    }

    DataTable dt = new DataTable();
    string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["AB_ReportEntities"].ConnectionString;
    using (SqlConnection cn = new SqlConnection(connStr))
    {

        SqlCommand cmd = new SqlCommand("FindIncomplete_Products", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@type", SqlDbType.NVarChar).Value = type;
        cmd.Parameters.Add("@category", SqlDbType.NVarChar).Value = category;
        cmd.Parameters.Add("@country", SqlDbType.NVarChar).Value = country;
        cmd.Parameters.Add("@subsidary", SqlDbType.NVarChar).Value = subsidary;
        cmd.Parameters.Add("@date", SqlDbType.Date).Value = mydate;

        SqlDataAdapter adp = new SqlDataAdapter(cmd);

        adp.Fill(dt);
    }

    return dt;
}

当 Date 字段在上述表单中具有空值时,我无法获得结果,我收到以下错误:

System.FormatException:字符串未被识别为有效的 DateTime。

4

3 回答 3

2

显然,将无法解析的值传递给 a将使用so useDateTime引发异常:DateTime.ParseDateTime.TryParse

DateTime.TryParse(String, DateTime) 方法与 DateTime.Parse(String) 方法类似,只是 TryParse(String, DateTime) 方法在转换失败时不会抛出异常。

来源:DateTime.TryParse

示例用法:

DateTime d2;
bool success = DateTime.TryParse(date.Text, out d2);
//if successful, d2 will be set to the value of the string.
于 2015-09-17T08:07:57.660 回答
2

像这样改变你的方法:

private DataTable GetData(string type, string category, string country, string subsidary,string date)
{
     DateTime? mydate = null;
     DateTime date2;
     bool check = DateTime.TryParse(date, out date2);
     if (check)
     {
         mydate = date2;
     }
}

然后这样称呼它:

DataTable dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, date.Text);
于 2015-09-17T08:09:35.657 回答
0

你可以使用这个扩展:

public static DateTime? TryGetDateTime(this string item, IFormatProvider provider = null)
{
    if (provider == null) provider = CultureInfo.CurrentCulture;
    DateTime dt;
    bool success = DateTime.TryParse(item, provider, DateTimeStyles.None, out dt);
    if (success) return dt;
    return null;
}

然后以这种方式更改您的方法调用:

DataTable dt = GetData(type.Text, 
                       category.Text,
                       subsidary.Text,
                       country.Text, 
                       date.Text.TryGetDateTime());
于 2015-09-17T08:12:08.237 回答