2011-04-21 37 views
0

我需要從標籤模板字段綁定到學生表中的StudentID的值。我想獲得StudentID值並將其插入到不同的表中。 這裏是我的GridView和SqlDataSource的:讀取模板字段標籤值綁定到sqlDatabase字段

<asp:GridView ID="GridView2" 
         style="position:absolute; top: 232px; left: 311px;" 
          AutoGenerateColumns="false" runat="server" 
         DataSourceID="SqlDataSource4"> 
         <Columns> 
          <asp:TemplateField> 
          <ItemTemplate > 
          <asp:CheckBox runat="server" ID="AttendanceCheckBox" /> 
          </ItemTemplate> 
          </asp:TemplateField> 
          <asp:TemplateField> 
          <ItemTemplate> 
          <asp:Label ID="studentIDLabel" Text='<%# Eval("StudentID") %>' runat="server"></asp:Label> 
          </ItemTemplate> 
          </asp:TemplateField>      
          <asp:BoundField DataField="Name" HeaderText="Name" /> 
         </Columns> 
        </asp:GridView> 

<asp:SqlDataSource ID="SqlDataSource4" runat="server" 
         ConnectionString="<%$ ConnectionStrings:RegisterConnectionString %>" 
         SelectCommand="SELECT [StudentID], [Name] FROM [Student] WHERE CourseID = @CourseID ">       
         <SelectParameters> 
          <asp:ControlParameter ControlID="CourseDropDownList" Name="CourseID" 
           PropertyName="SelectedValue" Type="Int32" /> 
         </SelectParameters> 
        </asp:SqlDataSource> 

這裏是我的代碼,它的後面插入值到另一個數據庫表:

protected void SaveRegisterButton_Click(object sender, EventArgs e) 
    { 
      SqlConnection connection; 
      SqlCommand command; 
      int numRowsAdded; 
      int id; 


    foreach (GridViewRow row in GridView2.Rows) 
    { 
     if (((CheckBox)row.FindControl("AttendanceCheckBox")).Checked) 
     { 
      try 
      { 
       bool attendance = true; 

       // Connecting to the database using the connection string in the web.config file 
       connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString); 

       // Create an INSERT Sql statement 
       // To prevent an Sql injection attack, we add parameters with names starting with an @ symbol 
       command = new SqlCommand("INSERT INTO Attendance(Present, StudentID, LessonID) VALUES(@Attendance, @StudentID, @LessonID)", connection); 

       command.Parameters.AddWithValue("@Attendance", attendance); 

任何人都可以幫助我的代碼中插入標籤模板內的價值字段(StudentID)插入考勤表的StudentID字段中。任何幫助非常感謝,提前感謝!

回答

1
foreach (GridViewRow row in GridView2.Rows) 
{ 
    if (((CheckBox)row.FindControl("AttendanceCheckBox")).Checked) 
    { 
Int32 StudentID = Convert.ToInt32(((Label)row.FindControl("studentIDLabel")).Text) 
.... 
.... 
} 
+0

感謝您的幫助我會檢查這段代碼,看它是否有效! – user715115 2011-04-21 14:19:16

+0

如果StudentID的數據類型爲nvarchar,該怎麼辦?什麼是nvarchar數據類型的C#數據類型? – user715115 2011-04-26 12:23:35

+0

弦........ – 2011-04-26 12:27:13