Reputation: 2115
I need check return datatable and count rows in my asp net GridView code.
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();
}
}
Upvotes: 0
Views: 1219
Reputation: 218798
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:
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:
Just remove the catch
block entirely and keep the try
and finally
. If you ever do need to re-throw an exception from a catch
block, just use the command:
throw;
This preserves the original exception, instead of replacing it with a new similar one.
Upvotes: 4