从Item模板中的Label获取文本

时间:2017-03-23 12:57:51

标签: c# asp.net

我目前正在从数据库中提取并且有2个标签显示正确的信息。但是我想在后面的代码中使用这些标签,但它们并没有出现在我面前。我在后面的代码中需要这个的原因是我可以将电子邮件地址插入收件人电子邮件。

下面是显示Item模板和SQL Datasource

的前端
<asp:SqlDataSource ID="userCourse" runat="server" ConnectionString='<%$ ConnectionStrings:ConnectionString %>' SelectCommand="SELECT DISTINCT tblCourse.courseTitle, tblCourse.advisorOfStudiesID, tblPersonalInfo.firstName, tblPersonalInfo.lastName, tblPersonalInfo.email FROM tblCourse INNER JOIN tblAdvisorOfStudies ON tblCourse.advisorOfStudiesID = tblAdvisorOfStudies.advisorOfStudiesID INNER JOIN tblUsers ON tblAdvisorOfStudies.userID = tblUsers.userID INNER JOIN tblPersonalInfo ON tblUsers.personalInfoID = tblPersonalInfo.personalInfoID WHERE (tblCourse.courseID = @userID)">
    <SelectParameters>
        <asp:SessionParameter SessionField="userID" Name="userID"></asp:SessionParameter>
    </SelectParameters>
</asp:SqlDataSource>
<asp:ListView ID="ListView1" runat="server" DataSourceID="userCourse">
    <ItemTemplate>
        <asp:Label ID="aosemail" runat="server" Text='<%# Eval("email") %>' />
        <asp:Label ID="aosname" hidden runat="server" Text='<%# Eval("firstName") %>' />
    </ItemTemplate>
</asp:ListView>    

下面是我想要获取标签文本的背后代码

private bool SendEmail()
{
    string recipient = aosemail; //AOS Email textbox should go here
    MailMessage mm = new MailMessage("CSC3047@gmail.com", recipient);
    mm.Subject = "Student has chosen Manual Enrollment Process!";
    //AOS name textbox will be here
    mm.Body = "Hi "   + aosename+ "<br><br>This is a quick email to inform you that " + Name.Text.ToString() + " has chosen the manual enrollment process. The reason we are emailing you is that you are their Advisor of Studies. Please email the user on " + Email.Text.ToString() + " <br><br>Regards";
    mm.IsBodyHtml = true;
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.EnableSsl = true;
    NetworkCredential NetworkCred = new NetworkCredential();
    NetworkCred.UserName = "*************";
    NetworkCred.Password = "*********";
    smtp.UseDefaultCredentials = true;
    smtp.Credentials = NetworkCred;
    smtp.Port = 587;
    smtp.Send(mm);
    return true;
} 

提前致谢

1 个答案:

答案 0 :(得分:0)

您需要使用FindContol来搜索ListView中的标签。因为可能有多个索引需要使用索引,就像数组一样。

int index = 0;

Label aosemail = ListView1.Items[index].FindControl("aosemail") as Label;
Label aosname = ListView1.Items[index].FindControl("aosname") as Label;

string body = "Hi " + aosname.Text + "<br><br>" + aosemail.Text;