2011-03-04 116 views
1

因此,我將一個遺留應用程序從coldfusion移植到asp.net/c#。我的問題是,(並且我已經全面搜索了它,但我可能不會正確地描述我的問題以獲得良好結果),是我想從我擁有的第一個查詢中獲取結果,並執行第二個查詢填寫該欄。根據第一個數據庫查詢做出第二個數據庫查詢

下面是如何在ColdFusion中做到了:

<cfquery name="p" datasource="db"> 
    select * from table 
</cfquery> 

<cfloop query="p"> 
    <tr> 
     <td> 
     <a href="page.cfm?id=#p.id#">#p.title#</a> 
     </td> 
     <td"> 
     #p.category# 
     </td> 
     <td> 
     #CreateObject("component","/components.dao").getuser(p.userid).user_fullname()# 
     </td> 
    </tr> 
</cfloop> 

你會發現我所說的組件和方法,我從查詢發送用戶ID了。此方法有另一個查詢調用單獨的數據庫,並返回該用戶的信息,在這種情況下是全名,而不僅僅是用戶標識。這是我有對我已經創建了下面的代碼asp.net/c#問題:

<asp:Repeater id="program_list" runat="server"> 
    <ItemTemplate> 
     <tr> 
     <td> 
      <a href="page.aspx?id=<%# Eval("id") %>"><%# Eval("title") %></a> 
     </td> 
     <td> 
      <%# Eval("category") %> 
     </td> 
     <td> 
      <%# Eval("userid")%> (needs full name convert) 
     </td> 
     </tr> 
    </ItemTemplate> 
</asp:Repeater> 

,並在代碼隱藏

protected void Page_Load(object sender, EventArgs e) 
{ 
    try 
    { 
     DbConnection connection = new SqlConnection(); 
     connection.ConnectionString = "***"; 
     connection.Open(); 

     SqlCommand cmd = (SqlCommand)connection.CreateCommand(); 
     cmd.CommandType = CommandType.Text; 
     cmd.CommandText = "SELECT * FROM table"; 

     SqlDataReader reader = null; 
     reader = cmd.ExecuteReader(); 
     program_list.DataSource = reader; 
     program_list.DataBind(); 
     reader.Close(); 
     connection.Close(); 
    } 
    catch (Exception ex) 
    { 
     Response.Write(ex); 
    } 
} 

正如你所看到的,它只做第一部分,輸出原始查詢,但我不知道如何與該查詢進行交互,以便第二次爲用戶詳細信息調用數據庫。任何想法將不勝感激,謝謝。

+0

我可能失去了一些東西,但是你就不能使用你的SQL聯接? – RandomWebGuy 2011-03-04 22:35:14

回答

0

所以你需要調用一個sql查詢中繼器的每一行。您應該使用ItemDataBoundEvent,在這種情況下,您可以處理行user_id並可以進行其他查詢。

例如

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) 
    { 
     DataRowView drw = (DataRowView)e.Item.DataItem 
     String sql = String.Format("Select * FROM UserInfo WHERE user_id={0}", drw["user_id"]); 


     Label lblUserName = (Label) e.Item.FindControl("lblUserName"); 
     lblUserName.Text = //WWhatever you get from query... 
    } 
+0

這絕對看起來像我需要,但DataRowView drw =(DataRowView)e.Item.DataItem'給出一個錯誤:'System.Data.Common.DataRecordInternal'鍵入'System.Data.DataRowView'任何想法是什麼? – Josh 2011-03-04 23:21:32

+0

System.Data.Common.DbDataRecord rd =(System.Data.Common.DbDataRecord)e.Item.DataItem;試試這個。 – adt 2011-03-04 23:35:55

+0

工作完美,謝謝。 – Josh 2011-03-04 23:48:29

0

您正在尋找ItemDataBound活動。您可以在該事件中執行查詢並填充其他控件。