繁体   English   中英

C#检查返回数据表

[英]c# check return datatable

我需要检查返回的数据表并在我的asp net GridView代码中对行进行计数

我尝试了此解决方案,但没有错误,但是代码未显示警报,也不计算行数。

我的代码如下。

我将非常感谢您在解决此问题方面可以给我的任何帮助。

public DataTable GridViewBind()
{
    sql = " SELECT * FROM tbl; ";

    try
    {
        dadapter = new OdbcDataAdapter(sql, conn);
        dset = new DataSet();
        dset.Clear();
        dadapter.Fill(dset);
        DataTable dt = dset.Tables[0];
        GridView1.DataSource = dt;
        GridView1.DataBind();
        return dt;

        if (dt.Rows.Count == 0)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('No data.');window.location='default.aspx';", true);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        dadapter.Dispose();
        dadapter = null;
        conn.Close();
    }
}

当然,代码不会显示警报。 在此之前,您要从方法中返回:

return dt;
// nothing after this will execute
if (dt.Rows.Count == 0)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('No data.');window.location='default.aspx';", true);
}

编译器应为此警告您。 不要忽略编译器警告。

您可以简单地将return语句移动到代码块的末尾:

if (dt.Rows.Count == 0)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('No data.');window.location='default.aspx';", true);
}
return dt;

旁注:您的catch块是:

  1. 丢弃有意义的堆栈跟踪信息
  2. 完全多余

只需卸下catch完全块,并保持tryfinally 如果确实需要从catch块重新抛出异常,则只需使用以下命令:

throw;

这将保留原始异常,而不是将其替换为新的相似异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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