[英]c# check return datatable
I need check return datatable and count rows in my asp net GridView code. 我需要检查返回的数据表并在我的asp net GridView代码中对行进行计数 。
I tried this solution, I don't have error but the code not showing the alert and not count the rows. 我尝试了此解决方案,但没有错误,但是代码未显示警报,也不计算行数。
My code below. 我的代码如下。
I would greatly appreciate any help you can give me in working this problem. 我将非常感谢您在解决此问题方面可以给我的任何帮助。
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();
}
}
Of course the code isn't showing the alert. 当然,代码不会显示警报。 You're returning from the method before that happens:
在此之前,您要从方法中返回:
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);
}
The compiler should be warning you about this. 编译器应为此警告您。 Don't ignore compiler warnings.
不要忽略编译器警告。
You can simply move your return
statement to the end of the code block: 您可以简单地将
return
语句移动到代码块的末尾:
if (dt.Rows.Count == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('No data.');window.location='default.aspx';", true);
}
return dt;
Side-note: Your catch
block is: 旁注:您的
catch
块是:
Just remove the catch
block entirely and keep the try
and finally
. 只需卸下
catch
完全块,并保持try
和finally
。 If you ever do need to re-throw an exception from a catch
block, just use the command: 如果确实需要从
catch
块重新抛出异常,则只需使用以下命令:
throw;
This preserves the original exception, instead of replacing it with a new similar one. 这将保留原始异常,而不是将其替换为新的相似异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.