2016-08-22 184 views
0

我實現了對我的嵌套gridview的搜索,並且All運行良好。但是當gridview加載時,它會在父表中顯示重複的行。Select statement顯示不正確的結果

enter image description here

正如你可以在圖片中看到,還有AC107的CourseID下2本書。但是我的Gridview在課程中爲每本教科書顯示一行。我搞砸了這個選擇語句,無論如何我改變它看看是否有任何工作,gridview不加載。

 protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      //i'm using a datatable for storing all the data 
      DataTable dt = new DataTable(); 
      string query = "select * from Course inner join textBooks on textBooks.CourseID = Course.CourseID"; 

      //wrapping in 'using' means the connection is closed an disposed when done 
      using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ToString())) 
      using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection)) 
      { 
       try 
       { 
        //fill the datatable with the contents from the database 
        adapter.Fill(dt); 
       } 
       catch 
       { 
       } 
      } 

      //save the datatable into a viewstate for later use 
      ViewState["allBooks"] = dt; 

      GridView1.DataSource = dt; 
      GridView1.DataBind(); 
     } 
    } 

下面是我的數據表格的佈局。

enter image description here

+0

千萬不要使用空的try-catch。 – LarsTech

回答

0

是(因爲你正在使用SqlConnection提供商類假設你使用SQL Server

SELECT * FROM (
select Course.*, 
ROW_NUMBER() OVER(PARTITION BY Course.CourseID ORDER BY Course.CourseID) AS rn 
from Course 
inner join textBooks 
on textBooks.CourseID = Course.CourseID) xxx 
WHERE rn = 1; 
你確定你的SQL查詢不能取你重複的行,使用 ROW_NUMBER()功能,看看它是如何工作的像
+0

我只是把它放在我當前查詢所在的報價單中? – user3487671

+0

是的......用你的當前查詢替換這個 – Rahul

+0

接收到這個錯誤:'System.Data.DataRowView'不包含名爲'thirteenISBN'的屬性。 – user3487671