2013-03-15 33 views
0

我有這樣的代碼時,按下一個按鈕叫:明確的價值

protected void Button1_Click(object sender, EventArgs e) 
{ 
    if (DropDownList1.SelectedItem.ToString() =="ER00 - File Header") 
    { 
     using (SqlConnection con = 
        new SqlConnection(ConfigurationSettings.AppSettings["DBcon"])) 
     { 
      if (String.IsNullOrEmpty(TextBox_ID.Text.ToString())) 
      { 
       lbl_NoBatchID.Text = "Please enter BatchID!"; 
      } 
      else 
      { 
       try 
       { 
        SqlCommand sqlCommand = new SqlCommand(
         "Select * from tbl_WinApps_FileHeader Where BatchID =" + 
         TextBox_ID.Text.ToString()); 

        sqlCommand.Connection = con; 
        con.Open(); 
        SqlDataReader read = sqlCommand.ExecuteReader(); 

        GridView1.DataSource = read; 
        GridView1.DataBind(); 
       } 
       catch (Exception) 
       {       
       } 
      } 
     } 
    } 
} 

這是它的工作原理:用戶輸入一個ID,然後按下按鈕時,它會顯示在表中SQL。

如果用戶沒有在文本框中輸入任何內容,它會提示「請輸入BatchID!」但在那之後,它會停留在那裏,即使我已經輸入了有效的ID,它也不會清除。任何想法,爲什麼?

+0

您可以嘗試設置lbl_NoBatchID.Text =「」。看到我的答案。 – 2013-03-15 02:08:18

回答

1

ASP.NET頁面有一些名爲ViewState,可以維護請求之間的控件的狀態。您需要清除GridView的DataSource值並重新綁定它。

  if (String.IsNullOrEmpty(TextBox_ID.Text.ToString())) 
      { 
       lbl_NoBatchID.Text = "Please enter BatchID!"; 
       GridView1.DataSource=null; 
       GridView1.DataBind(); 
      } 
      else 
      { 

你也想清除錯誤如果查找成功:

catch(Exception e){ 
} 
lbl_NoBatchID.Text = ""; 

我也應該注意到,你的空catch()會吞噬你可能得到的任何數據庫或查找錯誤。

1
protected void Button1_Click(object sender, EventArgs e) 
{ 
    if (DropDownList1.SelectedItem.ToString() =="ER00 - File Header") 
    { 

     using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["DBcon"])) 
     { 
      if (String.IsNullOrEmpty(TextBox_ID.Text.ToString())) 
      { 
       lbl_NoBatchID.Text = "Please enter BatchID!"; 

      } 
      else 
      { 
       try 
       { 

        SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader Where BatchID =" + TextBox_ID.Text.ToString()); 
        sqlCommand.Connection = con; 
        con.Open(); 
        SqlDataReader read = sqlCommand.ExecuteReader(); 

         GridView1.DataSource = read; 
         GridView1.DataBind(); 
        lbl_NoBatchID.Text = ""; 
       } 
       catch (Exception) 
       {       

       } 

      } 
     } 

    } 
+0

lbl_NoBatchID.Text =「」; – 2013-03-15 02:06:37

0

在你的Else塊添加這行代碼。

lbl_NoBatchID.Text = "";