2013-06-02 64 views
0

我想在asp.net中的同一個搜索頁上的gridview上顯示搜索結果。這裏是UI:Gridview不在asp.net中查看結果

enter image description here

這裏是我的代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    searchResults.DataBind(); 

} 
protected void BClassSearch_Click(object sender, EventArgs e) 
{ 
    // if (!IsPostBack) 
    //{ 
     SqlConnection con = new SqlConnection(); 
     con.ConnectionString = Userfunctions.GetConnectionString(); 
     con.Open(); 
     string selected = lbCourseListBox.SelectedValue; 

     if(selected!="" && Tcoursenumber.Text!="") 
     { 
      string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue+"' and CourseNumber = '" + Tcoursenumber.Text+"'"; 

      SqlDataAdapter adap = new SqlDataAdapter(query, con); 

      DataTable tab = new DataTable(); 

      adap.Fill(tab); 

      searchResults.DataSource = tab; 
      searchResults.DataBind(); 
     } 
     else if (selected != "" && Tcoursenumber.Text == "") 
     { 
      string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue; 

      SqlDataAdapter adap = new SqlDataAdapter(query, con); 

      DataTable tab = new DataTable(); 

      adap.Fill(tab); 

      searchResults.DataSource = tab; 
      searchResults.DataBind(); 
     } 
     else if (selected == "" && Tcoursenumber.Text != "") 
     { 
      string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseNumber='" + Tcoursenumber.Text; 

      SqlDataAdapter adap = new SqlDataAdapter(query, con); 

      DataTable tab = new DataTable(); 

      adap.Fill(tab); 

      searchResults.DataSource = tab; 
      searchResults.DataBind(); 
     } 
    //} 
    Response.Redirect("SearchCourse.aspx"); 
} 

的問題是,沒有搜索結果將顯示在GridView控件。誰能幫我這個?

感謝

回答

1

在按鈕的末尾刪除Response.Redirect("SearchCourse.aspx");點擊

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     // do you want to bind something in first time load? then load it here 
     // searchResults.DataSource = tab; 
     searchResults.DataBind(); 

    } 

} 

你不想給Response.Redirect打電話到相同的頁面,因爲當你點擊按鈕,它會投遞的頁面。如果您致電Response.Redirect它將加載新頁面,並且您將丟失頁面中的所有控件狀態。

+0

工作,謝謝。但是我不明白爲什麼它現在能夠工作,我的代碼和你的解決方案有什麼區別? – yrazlik

+1

@bigO'Response.Redirect'會再次加載您的頁面。你會失去搜索選擇等。 – Damith