Displaying another table field in GridView based on ID of record in another table
I currently have an SQL Table called Attendance and another table called Student. The attendance Table has the fields: AttendanceID, Date, Present, StudentID and Module ID. My student table has the fields StudentID and Name. One page in my application allows the user to enter the Students ID in a textbox where all the date, present, ModuleID from the Attendance Table are shown in a Gridview for the corresponding StudentID that is entered in the Textbox. Here is my code so far which works:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:RegisterConnectionString %>"
SelectCommand="SELECT * FROM [Attendance] WHERE ([StudentID] = @StudentID)">
<SelectParameters>
<asp:ControlParameter ControlID="pnumTextBox" Name="StudentID"
PropertyName="Text" Type="String" />
开发者_StackOverflow中文版 </SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server"
style="position:absolute; top: 241px; left: 357px; width: 356px;"
AutoGenerateColumns="False" DataKeyNames="AttendanceID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="AttendanceID" HeaderText="AttendanceID"
InsertVisible="False" ReadOnly="True" SortExpression="AttendanceID" />
<asp:CheckBoxField DataField="Present" HeaderText="Present"
SortExpression="Present" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="StudentID" HeaderText="StudentID"
SortExpression="StudentID" />
<asp:BoundField DataField="ModuleID" HeaderText="ModuleID"
SortExpression="ModuleID" />
</Columns>
</asp:GridView>
Along with displaying the AttendanceID, StudentID, ModuleID, Present, and Date, I need to display the Student Name field from the Student Table which has the same ID as entered in the textbox, how do I achieve this? I think it is possible to do this in the SELECT command but Im unsure how. Any help is appreciated, thanks in advance!
SELECT A.AttendanceID,A.Date,A.Present,A.ModuleID,S.StudentID,S.Name
FROM attendance A ,student S
WHERE A.StudentID = S.StudentID
AND S.StudentID = "Your Value from the textbox";
INNER JOIN
I prefer to use objectDataSource
rather than SQLDataSource
.
to separate your layers.and use parameterized query
to avoid sql injection and validate the user entry.
精彩评论