Ryan Ryan -4 years ago 93
ASP.NET (C#) Question

Get text from Label inside an Item template

I am currently pulling from the database and have the 2 labels showing the correct information. However I want to use these labels in the behind code but they are not showing up for me. The reason I need this in the behind code is so I can insert the email address to the recipient email.

Below is the front end showing the Item template and 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)">
<asp:SessionParameter SessionField="userID" Name="userID"></asp:SessionParameter>
<asp:ListView ID="ListView1" runat="server" DataSourceID="userCourse">
<asp:Label ID="aosemail" runat="server" Text='<%# Eval("email") %>' />
<asp:Label ID="aosname" hidden runat="server" Text='<%# Eval("firstName") %>' />

Below is the behind code in which I want to get the labels text

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;
return true;

Thanks in advance

Answer Source

You need to use FindContol to search for the Labels in the ListView. And since there could be more than one you have to use an index, just like an Array.

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download