2014-03-13 23 views
0

我正在爲我的工作場所的一些內部人員創建一個小型網絡工具。這個Web工具接受兩個輸入參數,這些參數通過我們的SQL服務器上的存儲過程發送。存儲的proc將兩個表格返回到Web工具中自己的GridView中。GridView錯誤處理

但是,我注意到如果存儲過程沒有爲一個或兩個結果表返回任何值,那麼該工具「爆炸」並給出運行時錯誤。如果表中沒有結果,我希望GridView(?)狀態表示沒有記錄返回。這裏是我到目前爲止的代碼:

protected void Button1_Click(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString); 

    con.Open(); 

    SqlCommand cmd; //Set up command variable 
    cmd = new SqlCommand("[dbo].[CSP]", con); //set command variable equal to CSP stored proc 
    cmd.CommandType = CommandType.StoredProcedure; //set command type as stored procedure 
    cmd.Parameters.Add(new SqlParameter("@customer_number", SqlDbType.NVarChar)).Value = TextBox1.Text; 
    cmd.Parameters.Add(new SqlParameter("@part_number", SqlDbType.NVarChar)).Value = TextBox2.Text; 

    if (TextBox1.Text == "" && TextBox2.Text == "") 
    { 
     lblMessage1.Text = "Please enter the Account & Part Numbers."; 
     lblMessage1.ForeColor = System.Drawing.Color.Red; 
    } 
    else if (TextBox1.Text == "" && TextBox2.Text != "") 
    { 
     lblMessage1.Text = "Please enter the Account Number."; 
     lblMessage1.ForeColor = System.Drawing.Color.Red; 
    } 

    else if (TextBox1.Text != "" && TextBox2.Text == "") 
    { 
     lblMessage1.Text = "Please enter the Part Number."; 
     lblMessage1.ForeColor = System.Drawing.Color.Red; 
    } 

    else 
    { 
     lblMessage1.Text = ""; 
     SqlDataAdapter adp = new SqlDataAdapter(); 
     DataSet ds1 = new DataSet(); 
     adp.SelectCommand = cmd; 
     adp.Fill(ds1); 
     GridView1.DataSource = ds1.Tables[0]; 
     GridView1.DataBind(); 
     GridView2.DataSource = ds1.Tables[1]; 
     GridView2.DataBind(); 

     con.Close(); 
    } 
} 

有人可以幫助我建立如何處理這個錯誤處理問題嗎?希望這很清楚。提前謝謝了。

+0

你得到的錯誤信息是什麼? – jadarnel27

回答

1
if (ds.Tables[0].Rows.Count > 0) 
{ 
    GridView1.DataSource = ds1.Tables[0]; 
    GridView1.DataBind(); 
} 

if (ds.Tables[1].Rows.Count > 0) 
{ 
    GridView2.DataSource = ds1.Tables[1]; 
    GridView2.DataBind(); 
} 
+0

非常感謝!我知道這很簡單,但無法弄清楚如何去做。 –

+1

好,趕上神戶。僅供參考 - 通常最好在你的答案中加入一些上下文/文本解釋,而不是僅僅編寫代碼。 – jadarnel27

0

你還沒有提到你的錯誤是什麼,所以我不能說那個。但是,如果要在GridView爲空時顯示一些自定義消息,則可以使用GridView's EmptyDataTemplate

<EmptyDataTemplate> 
    Move along, people - nothing to see here. 
</EmptyDataTemplate>