2014-07-11 44 views
0

我需要檢查回報在我的ASP淨GridView的代碼數據表count行C#檢查返回的數據表

我試過這個解決方案,我沒有錯誤,但代碼沒有顯示警報,也沒有統計行數。

我的代碼如下。

我將不勝感激任何幫助,你可以給我解決這個問題。

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(); 
    } 
} 

回答

4

當然代碼沒有顯示警報。在這種情況發生之前,您從方法中返回:

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. 完全多餘

J ust完全刪除catch區塊並保留tryfinally。如果你確實需要從catch塊重新拋出異常,只需要使用命令:

throw; 

這保留的,而不是用新的類似的一個替換它的原始異常。

+0

非常感謝。 – Hamamelis