Avatar of Tania_Farmer
Tania_Farmer asked on

email form asp.net BC30451 not declared

Hi,
I am trying to set up a small booking form with System.Net.Mail.  I am getting the following error:

Compiler Error Message: BC30451: Name 'txtsenderChecklist' is not declared.

MailBody = "Message:" & txtsenderMessage.Text & vbCrLf & vbCrLf
MailBody = "Which Courses? " & txtsenderChecklist.SelectedItem.Text & vbCrLf & vbCrLf
MailBody = "Contact Information:" &  txtsenderName.Text & vbnewline & txtsenderEmail.Text  & vbCrLf


I have a checklistbox with the various courses listed:
    <p>Which course(s) are you interested in?</p>
    <asp:Repeater ID="RepeaterBookingForm" DataSourceID="XmlSourceBooking" runat="server">
      <ItemTemplate>
        <p> <%# XPath ("@longName") %></p>
        <asp:CheckBoxList  id="txtsenderChecklist" runat="server"
  DataSource='<%# XPathSelect("course/@name") %> '
  DataTextField="value"
  DataValueField="value"
  AppendDataBoundItems="True" > </asp:CheckBoxList >
      </ItemTemplate>
     </asp:Repeater>

Any help is greatly appreciated.
Cheers
Tania
.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
Tania_Farmer

8/22/2022 - Mon
prairiedog

Since your CheckBoxList control is defined in the ItemTemplate within a Repeater, you can't directly use it.
ASKER
Tania_Farmer

oh - how do i use it properly for the form?  I have a list of courses to be selected that are being called from an xml file.
prairiedog

You can use the Repeater's ItemDataBound event handler to loop through each row and find the CheckBoxList control. In the event handler, you can do:
If (e.Item.ItemType = ListItemType.Item or e.Item.ItemType=ListItemType.AlternatingItem) then
   Dim cbl As CheckBoxList
   cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
   'You code to send email
End If
Your help has saved me hundreds of hours of internet surfing.
fblack61
ASKER
Tania_Farmer

HI,
Sorry beginner at this - that flew at supersonic speed over my head!

This is the only form on the site so have everything on the page.  This is what I have:

 Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click
 
    Const ToAddress As String = "tme@mydomain.com"

    '(1) Create the MailMessage instance
    Dim mm As New MailMessage(txtsenderEmail.Text, ToAddress)

    Dim MailBody As String
            MailBody = MailBody & "------------------------------------------------------------------------------------------------------------------"
            MailBody = "Message:" & txtsenderMessage.Text & vbCrLf & vbCrLf
            MailBody = "Which Courses? " & txtsenderChecklist.SelectedItem.Text & vbCrLf & vbCrLf
            MailBody = "Contact Information:" &  txtsenderName.Text & vbnewline & txtsenderEmail.Text  & vbCrLf
            MailBody = MailBody & "------------------------------------------------------------------------------------------------------------------"
        MailBody = MailBody & vbCrLf & vbCrLf & "OnCourse Booking Form"

    '(2) Assign the MailMessage's properties
    mm.Subject = "Contact /Booking Form Message"
    mm.Body = MailBody
    mm.IsBodyHtml = False

    '(3) Create the SmtpClient object
    Dim smtp As New SmtpClient("127.0.0.1")

    '(4) Send the MailMessage (will use the Web.config settings)
    smtp.Send(mm)

End Sub
</script>

Then in the page my repeater and checkboxlist are defined by xmlsource:
  <asp:XmlDataSource
        id="XmlSourceBooking"
        DataFile="/App_Data/courses.xml"
        runat="server"
        XPath="courses/category" />

Where do i place the EH loop code?

Cheers
Tania


ASKER
Tania_Farmer

Hi,
How do i get this to work?

Cheers
Tania
ASKER
Tania_Farmer

I am getting this error:  BC30456: 'Item' is not a member of 'System.EventArgs'.

Did the following:
Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click
If (e.Item.ItemType = ListItemType.Item or e.Item.ItemType=ListItemType.AlternatingItem) then
   Dim cbl As CheckBoxList
   cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
   'You code to send email

    Const ToAddress As String = "me@myaddress.com"
    '(1) Create the MailMessage instance
    Dim mm As New MailMessage(txtsenderEmail.Text, ToAddress) ......

Cheers
Tania
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
prairiedog

You put my code in the wrong place. I said in the Repeater's ItemDataBound even handler. Just double-click your Repeater control, and the ItemDataBound event handler will be created for you automatically, then put my code in the event handler.
prairiedog

Sorry, my bad. Don't double-click the Repeater to create the event handler. Do this instead:
1. Right-click your Repeater control and select Properties
2. In the Properties window, you will see an icon like a thunderbolt, and click the icon.
3. In the list of events, double-click ItemDataBound even.
4. Put the code in the ItemDataBound event handler block.

I was still waking up when I posted my previous comment. :-)
ASKER
Tania_Farmer

Hi,
That helped.  I moved everything to the vb.  it  has a little wiggle line and says txtsenderChecklist not declared:            MailBody = MailBody & "Which Courses? " & txtsenderChecklist.SelectedItem.Text & vbCrLf & vbCrLf



Partial Class Page
    Inherits System.Web.UI.Page

    Protected Sub Repeater2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater2.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cbl As CheckBoxList
            cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
            'You code to send email
        End If
    End Sub

    Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click

        Const ToAddress As String = "t@t.com"

        Try
            '(1) Create the MailMessage instance
            Dim mm As New MailMessage(ToAddress, ToAddress)
            Dim cbl1 As String
            Dim MailBody As String
            MailBody = MailBody & "Contact Information:" & vbnewline & txtsenderName.Text & vbnewline & txtsenderEmail.Text & vbnewline & txtsenderMessage.Text & vbcrlf
            MailBody = MailBody & "Which Courses? " & txtsenderChecklist.SelectedItem.Text & vbCrLf & vbCrLf
            MailBody = MailBody & "------------------------------------------------------------------------------------------------------------------" & vbcrlf
            MailBody = MailBody & "OnCourse Booking Form"
            mm.Subject = "Contact /Booking Form Message"
            mm.Body = MailBody
            mm.IsBodyHtml = False

            Dim smtp As New SmtpClient
            smtp.Send(mm)

        Catch smtpEx As SmtpException
            'A problem occurred when sending the email message
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a problem in sending the email: {0}');", smtpEx.Message.Replace("'", "\'")), True)
        Catch generalEx As Exception
            'Some other problem occurred
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a general problem: {0}');", generalEx.Message.Replace("'", "\'")), True)

        End Try
        Response.Redirect("/sent.aspx")
    End Sub
End Class

Cheers
Tania
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
prairiedog

Where do you place your SendEmail button?
ASKER
Tania_Farmer

Hi
At the bottom of the form:

...............  <p>Comments /suggested dates:<br />
    <asp:TextBox id="txtsenderMessage" TextMode="MultiLine" width="350px"  Rows="10" runat="server" />
  </p>
  <asp:RegularExpressionValidator
                    ID="RegularExpressionValidator1"
                    ControlToValidate="txtsenderEmail"
                    ErrorMessage="<p class='stop'><strong>**Please enter an email address value.</strong></p>"
                    SetFocusOnError="True"
                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    Display="Dynamic"
                    runat="server" />
  <asp:RequiredFieldValidator
                                ControlToValidate="txtsenderEmail"
                    ID="EmailRequired" runat="server"
                    ToolTip="E-mail is required." >
    <p class="stop"><strong>**Please check your email address.</strong></p>
  </asp:RequiredFieldValidator>
  <asp:button runat="server" id="SendEmail" Text="Send Details" />
</asp:content>
prairiedog

So you want you system to send out one single message with all selected items (even from different rows)?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Tania_Farmer

a single message - I have 8 courses listed from the xml file and would like the customer to tick which courses they are interested in. and send info in txt message.

T.

prairiedog

Here is what you need to do:
In your ItemDataBound event hander, when you find a selected item you need to store it in ViewState. Then in the SendEmail click event handler, you retrieve all selected items from the ViewSate.
Here is the steps in details:
1. For the ItemDataBoudn event handler:
Protected Sub Repeater2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater2.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cbl As CheckBoxList
            cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
           '+++++++++++++++++++++++++++++
            dim strItems as string = string.empty
            for i as integer = 0 to cbl.items.count - 1
                    If (cbl.Items(i).Selected = True) then
                       strItems = strItem & cbl.Items(i).Text & ", "
                    End If
             Next
             If (strItems <> String.Empty) then
                  ViewState("SelectedItems") = strItems
              End If
              '+++++++++++++++++++++++++++
        End If
    End Sub

2. For your SendEmail_Click event handler:
Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click
 
      ' Add following to retrieve all seleted items
     '+++++++++++++++++++++++++++++++++++++
       Dim strSelectedItems As String = String.Empty
       If (ViewState("SelectedItem") IsNot Nothing) AndAlso (ViewState("SelectedItem").ToString <> String.Empty) Then
           strSelectedItems = ViewState("SelectedItems").ToString()
       End If
      '++++++++++++++++++++++++++++++++++++++++

       'Continue your code until this line
        MailBody = MailBody & "Which Courses? " & strSelectedItems & vbCrLf & vbCrLf   '<====Change this lineEnd Sub
         'Continue your code
End Sub
ASKER
Tania_Farmer


Sorry - on strItems = strItem & cbl.Items(i).Text & ", "

I get a "strItem is not declared. " on the second item.

T

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
prairiedog

Sorry it's a typo. Should be "strItems". Basically, it is building a string with the selected items.
ASKER
Tania_Farmer

Hi,
That works great but now the email comes in without any courses listed.  I have a feeling its the way i set up my checkboxlist.  what is the common practice - should i start another question or just increase this one?

Cheers
Tania
prairiedog

You don't have to start a new question. What is your page_load event handler?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Tania_Farmer

don't laugh - or cry depending:

nothing....

Sub Page_Load(Src As Object, E As EventArgs)
If Not IsPostBack Then

End If
End Sub

Tania
prairiedog

Are you by any change using SqlDataSource to bind your Repeater?
ASKER
Tania_Farmer

no - xml:
 <asp:XmlDataSource
        id="XmlSourceBooking"
        DataFile="/App_Data/courses.xml"
        runat="server"
        XPath="courseList/category" EnableCaching="True" />
<asp:Repeater ID="RepeaterBookingForm" DataSourceID="XmlSourceBooking" runat="server">

It shows great in the form and tested online.  The email comes through but with none of the courses listed.



Cheers
Tanai
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER
Tania_Farmer

Could the problem be with the checkboxlist data references:
    <asp:CheckBoxList ID="txtsenderChecklist" runat="server" DataSource='<%# XPathSelect("product/@name") %> ' DataTextField="value" DataValueField="value" >
      </asp:CheckBoxList>

I don't have a "value" name:

<courseList>
  <category id="4wd"  longName="4wd Training" >
    <product code="lr"  name="4wd Bush Driving">
      <duration>1 Day</duration>
      <visible>true</visible>
......

    </product>
.......
When i use "value" the info shows up.  when i change to anything related to the xml nodes i get an error message.

T
prairiedog

For this line:
<asp:Repeater ID="RepeaterBookingForm" DataSourceID="XmlSourceBooking" runat="server">
Remove DataSourceID="XmlSourceBooking"
Then go to your Page_Load event handler, add it in the If Not Ispostback block:
Sub Page_Load(Src As Object, E As EventArgs)
If Not IsPostBack Then
   Me.RepaterBookingForm.DataSourceID = "XmlSourceBooking"
End If
End Sub
Then run your application to see if it helps.
ASKER
Tania_Farmer

hi,
the email coming back still shows up empty after - "which courses" .
T.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
prairiedog

hhm, I think it is because of this definition:
<asp:CheckBoxList ID="txtsenderChecklist" runat="server" DataSource='<%# XPathSelect("product/@name") %> ' DataTextField="value" DataValueField="value" >
      </asp:CheckBoxList>
When you specify the DataSource for the CheckboxList as above, the checkboxlist will be bound on every postback, in anohter word, it will discard all selected items. To test it, just step through you code and check this block:
for i as integer = 0 to cbl.items.count - 1
                    If (cbl.Items(i).Selected = True) then            ' <===Set a break point here
                       strItems = strItem & cbl.Items(i).Text & ", "
                    End If
             Next
             If (strItems <> String.Empty) then                        ' <=== Set another break point
                  ViewState("SelectedItems") = strItems
              End If
ASKER
Tania_Farmer

Hi
Set up the breakpoints - what do i look for?  
Also, have included all the code below:

test.aspx:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" Inherits="test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:XmlDataSource
        id="XmlSourceBooking"
        DataFile="~/App_Data/test.xml"
        runat="server"
        XPath="test/category"   />
       
       
  <h1>Option 1: Book by Email</h1>
  <p>Please email us at <a href="mailto:me@mydomain.com"><strong dir="ltr">
      me@mydomain.com</strong></a> and you will receive a reply shortly.</p>
  <p>&nbsp;</p>
  <h1>Option 2: Book by Form</h1>
  <p>Your name:    <asp:TextBox ID="txtsenderName" runat="server" Width="150px" />   </p>
  <p>Your email:     <asp:TextBox ID="txtsenderEmail" runat="server" Width="150px" />   </p>
  <p>Which course(s) are you interested in?</p>
    <asp:Repeater ID="Repeater2"  runat="server" DataSourceID="XmlSourceBooking"   >
 
  <ItemTemplate>  <p> <%# XPath ("@longName") %></p>
    <asp:CheckBoxList ID="txtsenderChecklist" runat="server"  DataSource='<%# XPathSelect("product/@name") %> ' DataTextField="value" DataValueField="value" >
      </asp:CheckBoxList>
 
     
  </ItemTemplate>
 
</asp:Repeater>

  <p>Comments /suggested dates:<br />
    <asp:TextBox id="txtsenderMessage" TextMode="MultiLine" width="350px"  Rows="10" runat="server" />
  </p>
  <asp:RegularExpressionValidator
                    ID="RegularExpressionValidator1"
                    ControlToValidate="txtsenderEmail"
                    ErrorMessage="<p class='stop'><strong>**Please enter an email address value.</strong></p>"
                    SetFocusOnError="True"
                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    Display="Dynamic"
                    runat="server" />
  <asp:RequiredFieldValidator
                                ControlToValidate="txtsenderEmail"
                    ID="EmailRequired" runat="server"
                    ToolTip="E-mail is required." >
    <p ><strong>**Please check your email address.</strong></p>
  </asp:RequiredFieldValidator>
  <asp:button runat="server" id="SendEmail" Text="Send Details" />
    </div>
    </form>
</body>
</html>

test.aspx.vb

Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml
Imports System.Xml.Xsl
Imports System.Xml.XPath
Imports System.Xml.XPath.XPathExpression
Imports System.Net.Mail



Partial Class test
    Inherits System.Web.UI.Page


    Protected Sub Repeater2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater2.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cbl As CheckBoxList
            cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
            '+++++++++++++++++++++++++++++
            Dim strItems As String = String.Empty
            For i As Integer = 0 To cbl.Items.Count - 1
                If (cbl.Items(i).Selected = True) Then
                    strItems = strItems & cbl.Items(i).Text & ", "
                End If
            Next
            If (strItems <> String.Empty) Then
                ViewState("SelectedItems") = strItems
            End If
            '+++++++++++++++++++++++++++
        End If
    End Sub

    Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click

        Const ToAddress As String = "me@mydomain.com"

        ' Add following to retrieve all seleted items
        '+++++++++++++++++++++++++++++++++++++
        Dim strSelectedItems As String = String.Empty
        If (ViewState("SelectedItem") IsNot Nothing) AndAlso (ViewState("SelectedItem").ToString <> String.Empty) Then
            strSelectedItems = ViewState("SelectedItems").ToString()
        End If
        '++++++++++++++++++++++++++++++++++++++++

        Try
            '(1) Create the MailMessage instance
            Dim mm As New MailMessage(ToAddress, ToAddress)

            Dim MailBody As String
            MailBody = MailBody & "Contact Information:" & vbNewLine & txtsenderName.Text & vbNewLine & txtsenderEmail.Text & vbNewLine & txtsenderMessage.Text & vbCrLf
            MailBody = MailBody & "Which Courses? " & strSelectedItems & vbCrLf & vbCrLf
            MailBody = MailBody & "------------------------------------------------------------------------------------------------------------------" & vbCrLf
            MailBody = MailBody & "OnCourse Booking Form"
            mm.Subject = "Contact /Booking Form Message"
            mm.Body = MailBody
            mm.IsBodyHtml = False

            Dim smtp As New SmtpClient("127.0.0.1")
            smtp.Send(mm)

        Catch smtpEx As SmtpException
            'A problem occurred when sending the email message
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a problem in sending the email: {0}');", smtpEx.Message.Replace("'", "\'")), True)
        Catch generalEx As Exception
            'Some other problem occurred
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a general problem: {0}');", generalEx.Message.Replace("'", "\'")), True)

        End Try
        Response.Redirect("/forms/sent.aspx")
    End Sub
End Class

/App_Data:  test.xml

<?xml version="1.0"?>
<test>
  <category id="4wd"  longName="4wd Training" >
    <product code="lr"  name="Bush Driving">   </product>
    <product code="hr" name="Defensive Driving">   </product>
    <product code="sr" name="Self-Recovery">    </product>
  </category>
</test>

and my web.config for now:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <customErrors mode="Off"/>
    <compilation defaultLanguage="VB" debug="true" />
    <pages enableViewState="false" />
  </system.web>
</configuration>


ASKER
Tania_Farmer

Hi,
Forgot to say - made up the above test files and it runs but the email still arrives with no ticked courses.  

T
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
prairiedog

Like I said in my post ID: 21671482, the cause of the empty couse list is that you have DataSource defined here:
<asp:CheckBoxList ID="txtsenderChecklist" runat="server"  DataSource='<%# XPathSelect("product/@name") %> ' DataTextField="value" DataValueField="value" >
      </asp:CheckBoxList>
I wanted you to set break points at those two places to verify that the variable "strItems" is actually empty even user selected items, thus no data is stored in the ViewState. As a result, the system sends out emails with empty list.
Please test it and let me know the result.
ASKER
Tania_Farmer

Hi,
Not sure what did it right: when I run it and click F5 a few times bouncing between the 2 toggle points the form comes up.  fill it out push send and again bounce between the toggle points.  Nothing looks different.

The only thing on the watch list is: !string '.' expected    
at: If (strItems <> String.Empty) Then...


prairiedog

Hold on. I have copied your code into my application and am working on it. Will get back to you when I'm done.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
prairiedog

Finanly I got this sorted out. Basically, when you declaratively specify DataSource or DataSourceID on a control, you make the application to re-bind the control on every postback. That is why you could not get the checked items of the check boxl list, because the checkboxlist control was rebound and lost all selections.
Here is the hack: when a check box is checked, use JavaScript to save the check box's value to a hidden field, then in your sendemail method, you can retrieve the values from the hidden field.
Here is the code:
1. In your data entry page(.aspx file), add this JavaScipt block in the <head> section:
    <script language="javascript" type="text/javascript">
       function SaveCheckedItems(checkBoxID, hiddenFieldID)
       {          
           var hiddenValue = document.getElementById(hiddenFieldID);          
           var tbody = document.getElementById(checkBoxID).childNodes[0];
           for(i=0; i<tbody.childNodes.length; i++)
           {
             td = tbody.childNodes[i].childNodes[0];
             var chk = td.childNodes[0];
             if (chk.checked)
             {
               if (hiddenValue.value.indexOf(td.childNodes[1].innerHTML) < 0)
               {
                hiddenValue.value = hiddenValue.value + td.childNodes[1].innerHTML + ", ";
               }
             }
             else
             {
               if (hiddenValue.value.indexOf(td.childNodes[1].innerHTML) >= 0)
               {
                    hiddenValue.value = hiddenValue.value.replace(td.childNodes[1].innerHTML + ",", "");
               }
             }            
           }
       }    
    </script>

2. Drag & drop a HiddenField control to your form, say named "hdnItems".
3. Change your ItemDataBound event handler as follows:
Protected Sub Repeater2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater2.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cbl As CheckBoxList
            cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
           
            For i As Integer = 0 To cbl.Items.Count - 1
                cbl.Items(i).Attributes.Add("onclick", "SaveCheckedItems('" & cbl.ClientID & "', '" & Me.hdnItems.ClientID & "')")
            Next
           
        End If
    End Sub

4. In your SendEmail_Click event handler, find this block:
           ' Add following to retrieve all seleted items
        '+++++++++++++++++++++++++++++++++++++
        Dim strSelectedItems As String = String.Empty
        If (ViewState("SelectedItem") IsNot Nothing) AndAlso (ViewState("SelectedItem").ToString <> String.Empty) Then
            strSelectedItems = ViewState("SelectedItems").ToString()
        End If
        '++++++++++++++++++++++++++++++++++++++++
and change the If/End If block to this sing line:
   strSelectedItems = Me.hdnItems.Value  

YOU ARE DONE!


ASKER
Tania_Farmer

Hi,
Sorry its still coming through empty.  

on :  Me.hdnItems  in the EH i get a little line saying hdnItems is not part of test.  
What I did was:

1. put javascript in here:
<head runat="server">
    <title>Untitled Page</title>
  <script language="javascript" type="text/javascript">
    ...   function SaveCheckedItems(checkBoxID, hiddenFieldID)
       {          .....
    </script>
</head>
<body>
    <form id="form1" runat="server">  ...
2 Put in hidden field called hdnItems:

  <asp:HiddenField runat="server" id="hdnItems"  />
     
    <div>
     <asp:XmlDataSource
        id="XmlSourceBooking"
        DataFile="~/App_Data/test.xml"
        runat="server"
        XPath="test/category"   />
       <h1>Option 2: Book by Form</h1>
  <p>Your name:    <asp:TextBox ID="txtsenderName" runat="server" Width="150px" />   </p>
  <p>Your email:     <asp:TextBox ID="txtsenderEmail" runat="server" Width="150px" />   </p>
  <p>Which course(s) are you interested in?</p>
     
    <asp:Repeater ID="Repeater2"  runat="server" DataSourceID="XmlSourceBooking"   >
 
  <ItemTemplate>  <p> <%# XPath ("@longName") %></p>
    <asp:CheckBoxList ID="txtsenderChecklist" runat="server"  DataSource='<%# XPathSelect("product/@name") %> ' DataTextField="value" DataValueField="value" >
      </asp:CheckBoxList>
  </ItemTemplate>
</asp:Repeater>

  <p>Comments /suggested dates:<br />
    <asp:TextBox id="txtsenderMessage" TextMode="MultiLine" width="350px"  Rows="10" runat="server" />
  </p>
  <asp:button runat="server" id="SendEmail" Text="Send Details" />
    </div>
    </form>
</body>
</html>

3.  changed event handlers: in 2 locations.
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml
Imports System.Xml.Xsl
Imports System.Xml.XPath
Imports System.Xml.XPath.XPathExpression
Imports System.Net.Mail



Partial Class test
    Inherits System.Web.UI.Page


    Protected Sub Repeater2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater2.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cbl As CheckBoxList
            cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)

            For i As Integer = 0 To cbl.Items.Count - 1
                cbl.Items(i).Attributes.Add("onclick", "SaveCheckedItems('" & cbl.ClientID & "', '" & Me.hdnItems.ClientID & "')")
            Next

        End If
    End Sub


    Protected Sub SendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SendEmail.Click

        Const ToAddress As String = "me@mydomain.com"

        ' Add following to retrieve all seleted items
        '+++++++++++++++++++++++++++++++++++++
        Dim strSelectedItems As String = String.Empty
        strSelectedItems = Me.hdnItems.Value
        '++++++++++++++++++++++++++++++++++++++++

        Try
            '(1) Create the MailMessage instance
            Dim mm As New MailMessage(ToAddress, ToAddress)

            Dim MailBody As String
            MailBody = MailBody & "Contact Information:" & vbNewLine & txtsenderName.Text & vbNewLine & txtsenderEmail.Text & vbNewLine & txtsenderMessage.Text & vbCrLf
            MailBody = MailBody & "Which Courses? " & strSelectedItems & vbCrLf & vbCrLf
            MailBody = MailBody & "------------------------------------------------------------------------------------------------------------------" & vbCrLf
            MailBody = MailBody & "OnCourse Booking Form"
            mm.Subject = "Contact /Booking Form Message"
            mm.Body = MailBody
            mm.IsBodyHtml = False

            Dim smtp As New SmtpClient("127.0.0.1")
            smtp.Send(mm)

        Catch smtpEx As SmtpException
            'A problem occurred when sending the email message
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a problem in sending the email: {0}');", smtpEx.Message.Replace("'", "\'")), True)
        Catch generalEx As Exception
            'Some other problem occurred
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a general problem: {0}');", generalEx.Message.Replace("'", "\'")), True)

        End Try
        Response.Redirect("sent.aspx")
    End Sub
End Class
ASKER
Tania_Farmer

ignore part about squiggle line  - gone.

t
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
prairiedog

Are you sure you got an empty email? I could run my application without any problems and got an email like this:
Contact Information:

myemailaddress@domain.com

Which Courses? Bush Driving, Defensive Driving, Self-Recovery,

------------------------------------------------------------------------------------------------------------------
OnCourse Booking Form

Anyway, here is my source code, you can take a look at it to see why yours is not working. My page is named Default.aspx
' ASPX file of default.aspx:
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Default.aspx.vb" Inherits="WebApplication1._Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
       function SaveCheckedItems(checkBoxID, hiddenFieldID)
       {
           
           var hiddenValue = document.getElementById(hiddenFieldID);
           
           var tbody = document.getElementById(checkBoxID).childNodes[0];
           for(i=0; i<tbody.childNodes.length; i++)
           {
             td = tbody.childNodes[i].childNodes[0];
             var chk = td.childNodes[0];
             if (chk.checked)
             {
               if (hiddenValue.value.indexOf(td.childNodes[1].innerHTML) < 0)
               {
                hiddenValue.value = hiddenValue.value + td.childNodes[1].innerHTML + ", ";
               }
             }
             else
             {
               if (hiddenValue.value.indexOf(td.childNodes[1].innerHTML) >= 0)
               {
                    hiddenValue.value = hiddenValue.value.replace(td.childNodes[1].innerHTML + ",", "");
               }
             }             
           }
           alert(hiddenValue.value);
       }
    
    </script>
</head>
 
<body>
    <form id="form1" runat="server">
        <div>
        
        <asp:XmlDataSource
        id="XmlSourceBooking"
        DataFile="~/App_Data/test.xml"
        runat="server"
        XPath="test/category"   />
            &nbsp;
        
        
        <asp:HiddenField ID="hdnItems" runat="server" />
         
  <h1>Option 1: Book by Email</h1>
  <p>Please email us at <a href="mailto:me@mydomain.com"><strong dir="ltr">
      me@mydomain.com</strong></a> and you will receive a reply shortly.</p>
  <p>&nbsp;</p>
  <h1>Option 2: Book by Form</h1>
  <p>Your name:    <asp:TextBox ID="txtsenderName" runat="server" Width="150px" />   </p>
  <p>Your email:     <asp:TextBox ID="txtsenderEmail" runat="server" Width="150px" />   </p>
  <p>Which course(s) are you interested in?</p>
    <asp:Repeater ID="Repeater2"  runat="server" DataSourceID="XmlSourceBooking"   >
 
  <ItemTemplate>  <p> <%# XPath ("@longName") %></p>
    <asp:CheckBoxList ID="txtsenderChecklist" runat="server" DataSource='<%# XPathSelect("product/@name") %> ' DataTextField="value" DataValueField="value"  >
      </asp:CheckBoxList>
 
     
  </ItemTemplate>
 
</asp:Repeater>
 
  <p>Comments /suggested dates:<br />
    <asp:TextBox id="txtsenderMessage" TextMode="MultiLine" width="350px"  Rows="10" runat="server" />
  </p>
  <asp:RegularExpressionValidator
                    ID="RegularExpressionValidator1"
                    ControlToValidate="txtsenderEmail"
                    ErrorMessage="<p class='stop'><strong>**Please enter an email address value.</strong></p>"
                    SetFocusOnError="True" 
                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    Display="Dynamic"
                    runat="server" />
  <asp:RequiredFieldValidator 
                                ControlToValidate="txtsenderEmail" 
                    ID="EmailRequired" runat="server" 
                    ToolTip="E-mail is required." >
    <p ><strong>**Please check your email address.</strong></p>
  </asp:RequiredFieldValidator>
  <asp:button runat="server" id="SendEmail" Text="Send Details" />
 
        </div>
    </form>
</body>
</html>
 
'Code-behine of default.aspx
Imports System.Data.SqlClient
Imports System.Configuration
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml
Imports System.Xml.Xsl
Imports System.Xml.XPath
Imports System.Xml.XPath.XPathExpression
Imports System.Net.Mail
 
 
Partial Public Class _Default
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        
    End Sub
 
    Protected Sub Repeater2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater2.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cbl As CheckBoxList
            cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
            
            For i As Integer = 0 To cbl.Items.Count - 1
                cbl.Items(i).Attributes.Add("onclick", "SaveCheckedItems('" & cbl.ClientID & "', '" & Me.hdnItems.ClientID & "')")
            Next
            
        End If
    End Sub
 
 
    Protected Sub SendEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendEmail.Click
        Const ToAddress As String = "my@domain.com"
 
        ' Add following to retrieve all seleted items
        '+++++++++++++++++++++++++++++++++++++
        Dim strSelectedItems As String = String.Empty
        strSelectedItems = Me.hdnItems.Value
        'If (ViewState("SelectedItem") IsNot Nothing) AndAlso (ViewState("SelectedItem").ToString <> String.Empty) Then
        '    strSelectedItems = ViewState("SelectedItems").ToString()
        'End If
        '++++++++++++++++++++++++++++++++++++++++
 
        Try
            '(1) Create the MailMessage instance
            Dim mm As New MailMessage(ToAddress, ToAddress)
 
            Dim MailBody As String = String.Empty
            MailBody = MailBody & "Contact Information:" & vbNewLine & txtsenderName.Text & vbNewLine & txtsenderEmail.Text & vbNewLine & txtsenderMessage.Text & vbCrLf
            MailBody = MailBody & "Which Courses? " & strSelectedItems & vbCrLf & vbCrLf
            MailBody = MailBody & "------------------------------------------------------------------------------------------------------------------" & vbCrLf
            MailBody = MailBody & "OnCourse Booking Form"
            mm.Subject = "Contact /Booking Form Message"
            mm.Body = MailBody
            mm.IsBodyHtml = False
 
            Dim smtp As New SmtpClient("server.subdomain.mydomain.dom")
            smtp.Send(mm)
 
        Catch smtpEx As SmtpException
            'A problem occurred when sending the email message
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a problem in sending the email: {0}');", smtpEx.Message.Replace("'", "\'")), True)
        Catch generalEx As Exception
            'Some other problem occurred
            ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a general problem: {0}');", generalEx.Message.Replace("'", "\'")), True)
 
        End Try
        Response.Redirect("sent.aspx")
 
    End Sub
End Class

Open in new window

ASKER
Tania_Farmer

Hi,
The only difference that I can find is you used: Codebehind="Default.aspx.vb"
and I used  CodeFile="Default.aspx.vb".  Would that make a difference?

When I receive the email I get:
Contact Information:
tania
tania@mydomain.com
Which Courses?

------------------------------------------------------------------------------------------------------------------
OnCourse Booking Form

Its always empty below.
T
prairiedog

Post your source code (.aspx and .vb files) here and let me take a look.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Tania_Farmer

Hi,
My config file as the moment has:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <customErrors mode="Off"/>
    <compilation defaultLanguage="VB" debug="true" />
    <pages enableViewState="false" >
     
    </pages>
  </system.web>
</configuration>


Also, when I tick the checkbox list i get an error message - every time its checked or unchecked.  A windows alert message comes up with a warning  at http localstate 2215 says and then the message is empty.

Cheers
Tania
<%@ Page Language="vb" AutoEventWireup="false"  EnableViewState="true" CodeFile="test2.aspx.vb" Inherits="test2" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
       function SaveCheckedItems(checkBoxID, hiddenFieldID)
       {
           
           var hiddenValue = document.getElementById(hiddenFieldID);
           
           var tbody = document.getElementById(checkBoxID).childNodes[0];
           for(i=0; i<tbody.childNodes.length; i++)
           {
             td = tbody.childNodes[i].childNodes[0];
             var chk = td.childNodes[0];
             if (chk.checked)
             {
               if (hiddenValue.value.indexOf(td.childNodes[1].innerHTML) < 0)
               {
                hiddenValue.value = hiddenValue.value + td.childNodes[1].innerHTML + ", ";
               }
             }
             else
             {
               if (hiddenValue.value.indexOf(td.childNodes[1].innerHTML) >= 0)
               {
                    hiddenValue.value = hiddenValue.value.replace(td.childNodes[1].innerHTML + ",", "");
               }
             }             
           }
           alert(hiddenValue.value);
       }
    
    </script>
</head>
 
<body>
    <form id="form1" runat="server">
        <div>
        
        <asp:XmlDataSource
        id="XmlSourceBooking"
        DataFile="~/App_Data/test.xml"
        runat="server"
        XPath="test/category"   />
           
        
        
<asp:HiddenField ID="hdnItems" runat="server" />
         
  <h1>Option 2: Book by Form</h1>
  <p>Your name:    <asp:TextBox ID="txtsenderName" runat="server" Width="150px" />   </p>
  <p>Your email:     <asp:TextBox ID="txtsenderEmail" runat="server" Width="150px" />   </p>
  <p>Which course(s) are you interested in?</p>
    <asp:Repeater ID="Repeater2"  runat="server" DataSourceID="XmlSourceBooking"   >
 
  <ItemTemplate>  <p> <%# XPath ("@longName") %></p>
    <asp:CheckBoxList ID="txtsenderChecklist" runat="server" DataSource='<%# XPathSelect("product/@name") %> ' DataTextField="value" DataValueField="value"  >
      </asp:CheckBoxList>
 
     
  </ItemTemplate>
 
</asp:Repeater>
 
  <p>Comments /suggested dates:<br />
    <asp:TextBox id="txtsenderMessage" TextMode="MultiLine" width="350px"  Rows="10" runat="server" />
  </p>
  <asp:RegularExpressionValidator
                    ID="RegularExpressionValidator1"
                    ControlToValidate="txtsenderEmail"
                    ErrorMessage="<p class='stop'><strong>**Please enter an email address value.</strong></p>"
                    SetFocusOnError="True" 
                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                    Display="Dynamic"
                    runat="server" />
  <asp:RequiredFieldValidator 
                                ControlToValidate="txtsenderEmail" 
                    ID="EmailRequired" runat="server" 
                    ToolTip="E-mail is required." >
    <p ><strong>**Please check your email address.</strong></p>
  </asp:RequiredFieldValidator>
  <asp:button runat="server" id="SendEmail" Text="Send Details" />
 
        </div>
    </form>
</body>
</html>
 
'----------------------------------
 
Imports System.Configuration
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml
Imports System.Xml.Xsl
Imports System.Xml.XPath
Imports System.Xml.XPath.XPathExpression
Imports System.Net.Mail
 
 
Partial Public Class test2
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
    End Sub
 
    Protected Sub Repeater2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater2.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cbl As CheckBoxList
            cbl = CType(e.Item.FindControl("txtsenderChecklist"), CheckBoxList)
 
            For i As Integer = 0 To cbl.Items.Count - 1
                cbl.Items(i).Attributes.Add("onclick", "SaveCheckedItems('" & cbl.ClientID & "', '" & Me.hdnItems.ClientID & "')")
            Next
 
        End If
    End Sub
 
 
    Protected Sub SendEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendEmail.Click
        Const ToAddress As String = "my@domain.com"
 
        ' Add following to retrieve all seleted items
        '+++++++++++++++++++++++++++++++++++++
        Dim strSelectedItems As String = String.Empty
        strSelectedItems = Me.hdnItems.Value
 
        '++++++++++++++++++++++++++++++++++++++++
 
        '(1) Create the MailMessage instance
        Dim mm As New MailMessage(ToAddress, ToAddress)
 
        Dim MailBody As String = String.Empty
        MailBody = MailBody & "Contact Information:" & vbNewLine & txtsenderName.Text & vbNewLine & txtsenderEmail.Text & vbNewLine & txtsenderMessage.Text & vbCrLf
        MailBody = MailBody & "Which Courses? " & strSelectedItems & vbCrLf & vbCrLf
        MailBody = MailBody & "------------------------------------------------------------------------------------------------------------------" & vbCrLf
        MailBody = MailBody & "OnCourse Booking Form"
        mm.Subject = "Contact /Booking Form Message"
        mm.Body = MailBody
        mm.IsBodyHtml = False
 
        Dim smtp As New SmtpClient("127.0.0.1")
        smtp.Send(mm)
 
        Response.Redirect("sent.aspx")
 
    End Sub
End Class

Open in new window

ASKER CERTIFIED SOLUTION
prairiedog

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Tania_Farmer

Hi,
Thats it - IT WORKED!  Thank-you so much for your persistence.  

Its perfect.  

Cheers
Tania