2015-12-01 117 views
0

我有一個下拉菜單與買家列表,我試圖根據用戶在下拉列表中選擇將sql查詢結果綁定到列表視圖。下面是代碼,但是listview完全不顯示。基於下拉列表選擇在列表視圖中顯示sql結果

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

     SqlCommand cmd = new SqlCommand("SELECT Team_Name FROM Team WHERE Team_ID = @Team_ID", con); 
     cmd.Parameters.AddWithValue("@Team_ID", DropDownListSearchByBuyer.Text); 
     con.Open(); 



     var reader = cmd.ExecuteReader(); 

     ListView1.DataSource = reader; 
     ListView1.DataBind(); 

    } 

列表視圖代碼

<asp:ListView ID="ListView1" runat="server"> 
    </asp:ListView> 
+1

,能得到任何異常後?你的列表視圖設計代碼在哪裏? –

+0

我沒有得到任何異常,它加載正常。請參閱上面的編輯列表視圖代碼 – Haldamir

+0

放置一個斷點並逐步查看您是否從數據庫中獲得任何值 – Izzy

回答

0

在列表視圖添加ItemTemplate中用於顯示欄等下方。

<asp:ListView ID="ListView1" runat="server"> 
    <ItemTemplate> 
      <span><%# Eval("Team_Name") %><span> 
    </ItemTemplate> 
</asp:ListView> 

更多細節請參見文章:https://msdn.microsoft.com/en-us/library/bb398790.aspx

+0

不幸的是沒有修復它。仍然不加載列表視圖。 – Haldamir

+0

檢查你的閱讀器變量是否包含任何數據? –

0
void SetListView() 
    { 
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString); 

     SqlCommand cmd = new SqlCommand("SELECT Team_Name FROM Team WHERE Team_ID = @Team_ID", con); 
     cmd.Parameters.AddWithValue("@Team_ID", DropDownListSearchByBuyer.Text); 
     con.Open(); 
     var reader = cmd.ExecuteReader(); 
     var readerdata = GetReaderData(reader); 
     reader.Close(); 
     reader = null; 
     con.Close(); 
     con = null; 

     ListView1.DataSource = readerdata; 
     ListView1.DataBind(); 
    } 

    DataTable GetReaderData(IDataReader reader) 
    { 
     DataTable dtSchema = reader.GetSchemaTable(); 
     DataTable readerData = new DataTable(); 

     if (dtSchema == null) 
     { 
      return readerData; 
     } 

     for (int i = 0; i < dtSchema.Rows.Count; i++) 
     { 
      DataColumn dc = new DataColumn(); 
      dc.ColumnName = dtSchema.Rows[i]["ColumnName"].ToString(); 
      readerData.Columns.Add(dc); 
     } 


     while (reader.Read()) 
     { 
      DataRow dr = readerData.NewRow(); 

      for (int i = 0; i < readerData.Columns.Count; i++) 
      { 
       dr[readerData.Columns[i].ColumnName] = reader[readerData.Columns[i].ColumnName]; 
      } 
      readerData.Rows.Add(dr); 
     } 

     return readerData; 
    } 

始終Close閱讀器讀取數據

相關問題