[英]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
块是:
只需卸下catch
完全块,并保持try
和finally
。 如果确实需要从catch
块重新抛出异常,则只需使用以下命令:
throw;
这将保留原始异常,而不是将其替换为新的相似异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.