2011-05-05 86 views
0


我有一個學生註冊gridview填充了註冊對象。註冊對象具有學生ID。使用該ID,我填充了2個註冊gridview的列(來自Student對象的3個屬性)。
現在,我正在用下面的代碼。這意味着3次往返數據庫的同一個對象,這是非常糟糕的。我如何使用同一個對象來獲得3個屬性?C# - 在GridView中爲多個列使用相同的對象

<asp:TemplateField HeaderText="Student Name"> 
       <ItemTemplate> 
        <asp:Label ID="lblName" runat="server" Text='<%# string.Format("{0} - {1}", StudentProfile.GetStudentProfileById(Convert.ToInt32(Eval("StudentId"))).FirstName, StudentProfile.GetStudentProfileById(Convert.ToInt32(Eval("StudentId"))).Surname) %>'></asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="Student DOB"> 
       <ItemTemplate> 
        <asp:Label ID="lblDOB" runat="server" Text='<%# StudentProfile.GetStudentProfileById(Convert.ToInt32(Eval("StudentId"))).DateOfBirth %>'></asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 

編輯:僅供參考,我要處理更新,這將涉及添加文本框等每一行GridView的行。你可以保留這個答案嗎?

非常感謝!

回答

2

你綁定數據到gridview的方式是錯誤的。您需要在對象/集合中獲取Data,然後將該數據作爲DataSource綁定到GridView

看看這裏Displaying Data With the ObjectDataSource,並在這個看起來也Querying Data with the SqlDataSource Control

+0

你的意思是我應該創建一個類來存儲,通過GridView的列反映中間對象? – 2011-05-05 06:25:23

+1

您可以從數據庫一次獲取所有數據,然後將其放入一些集合/數據表,然後將該集合/數據表綁定到您的grdivew – 2011-05-05 06:53:59

相關問題