ASP VB.NET: Need help Inserting data and sending notification email from web form

I am new to .NET and I can't figure out what I am doing wrong here.  I need to get this form to insert the data and then send out an auto notification email.  I am getting the error: System.NullReferenceException: Object variable or With block variable not set.  
Please help!

-----------------------------------------------------------------------------
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.Odbc" %>
<%@ Import Namespace="System.Net.Mail" %>

<script language="VB" runat="server">
 
    Dim connStr As String = ConfigurationManager.AppSettings("DSN1").ToString()
    Dim dbconn As New OdbcConnection(connStr)
    Dim sql As Object
    Dim dbcomm As Object
    Dim dbread As Object

    Sub Page_Load()
        Select Request("ToDo")

            '***********
            Case "NewReg"
                '***********
                dbconn.Open()
                sql = "SELECT * FROM Events WHERE id=" & Int(Request("id"))
                dbcomm = New OdbcCommand(sql, dbconn)
                dbread = dbcomm.ExecuteReader()
                NewReg.DataSource = dbread
                NewReg.DataBind()


            '***********
            Case "WriteNew"
                '***********
                       
                dbconn.Open()
               
                sql = "INSERT INTO Customers(First_Name, Last_Name, Job_Title, Company_Name, Work_Phone, Registrant_Email) VALUES ('" & First_Name.Text & "','" & Last_Name.Text & "','" & Job_Title.Text & "','" & Company_Name.Text & "','" & Work_Phone.Text & "','" & Registrant_Email.Text & "')"
                dbcomm = New OdbcCommand(sql, dbconn)
                dbcomm.ExecuteNonQuery()
               
                dbconn.Close()
                                               
                Dim sMsg As String
                sMsg += "<HTML>" & vbCrLf
                sMsg += "<BODY>" & vbCrLf
                sMsg += "New Registration Submitted:<br /><br />" & vbCrLf
                sMsg += "<table><tr><td>Registrant Name:</td><td>" & First_Name.Text & "&nbsp;" & Last_Name.Text & "</td></tr>" & vbCrLf
                sMsg += "<tr><td>Email Address:</td><td><a href='mailto:" & Registrant_Email.Text & "'>" & Registrant_Email.Text & "</a></td></tr>" & vbCrLf
                sMsg += "<tr><td>Company Name:</td><td>" & Company_Name.Text & "</td></tr>" & vbCrLf
                sMsg += "<tr><td>Work Phone:</td><td>" & Work_Phone.Text & "</td></tr></table>" & vbCrLf
                sMsg += "</BODY>" & vbCrLf
                sMsg += "</HTML>" & vbCrLf
               
                Dim objEmail As New MailMessage
                Dim Recipient As MailAddress = New MailAddress(Registrant_Email.Text)
                Dim SendBCC As MailAddress = New MailAddress("email@website.com")
                objEmail.To.Add(Recipient)
                objEmail.Bcc.Add(SendBCC)
                objEmail.From = New MailAddress("noreply@website.com")
                objEmail.Subject = "Here's the subject of the email"
                objEmail.Body = sMsg
                objEmail.IsBodyHtml = True
                Dim smtp As New SmtpClient("x.x.x.x")
                smtp.Send(objEmail)

        End Select
    End Sub

</script>

----------------------------------------------------------------

<asp:DataList id="NewReg" runat="server">
<ItemTemplate>

      <div><br />Event Registration</div>
      <div style="width:100%;text-align:center;margin:auto;">
            <div style="width:600px;">
                  <div>
                        <div style="float:left;">Event Title:</div>
                        <div style="float:left;">"<%# Container.DataItem("Event_Title")%>"</div>
            </div>
      </div>

<script language="javascript" type="text/javascript">
          function validar() {
              errores = '';
              if (document.register.First_Name.value == '') errores = errores + 'First Name\n';
              if (document.register.Last_Name.value == '') errores = errores + 'Last Name\n';
              if (document.register.Company_Name.value == '') errores = errores + 'Company Name\n';
              if (document.register.Work_Phone.value == '') errores = errores + 'Work Phone\n';
            if (document.register.Registrant_Email.value == '') errores = errores + 'Email Address\n';
              }
          

</script>
<div>
            <form method="post" action="register.aspx?ToDo=WriteNew&id=<%# request.QueryString("id")%>" name="regform" onsubmit="return validar();">
           
                  <div>
                        <div style="float:left;">First Name:</div>
                        <div style="float:left;"><input name="First_Name" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Last Name:</div>
                        <div style="float:left;"><input name="Last_Name" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Company Name:</div>
                        <div style="float:left;"><input name="Company_Name" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Phone:</div>
                        <div style="float:left;"><input name="Work_Phone" type="text" style="width:140px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Email Address:</div>
                        <div style="float:left;"><input name="Registrant_Email" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <br /><input type="image" src="images/submit.gif" alt="" />
                  </div>
                  
            </form>
</div>
</ItemTemplate>
</asp:DataList>

RegedekAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

 
Daniel ReynoldsSoftware Applications Developer / IntegratorCommented:
Have you ran this in debug mode to figure out where it is getting the Null Reference from? That would help us help you.
0
 
RegedekAuthor Commented:
Does this help any?

This is the line that's getting the error:

145: sql = "INSERT INTO Customers(First_Name, Last_Name, Job_Title, Company_Name, Work_Phone, Registrant_Email) VALUES ('" & First_Name.Text & "','" & Last_Name.Text & "','" & Job_Title.Text & "','" & Company_Name.Text & "','" & Work_Phone.Text & "','" & Registrant_Email.Text & "')"

Suggestions from Visual Web Dev:

1. Use the "new" keyword to create an object instance.
2. Check to determine if the object is null before calling the method.

"In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user."


Stack Trace:
System.NullReferenceException was unhandled by user code
  Message=Object variable or With block variable not set.
  Source=Microsoft.VisualBasic
  StackTrace:
       at Microsoft.VisualBasic.CompilerServices.Symbols.Container..ctor(Object Instance)
       at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
       at ASP.register_aspx.Page_Load() in C:\Inetpub\wwwroot\register.aspx:line 145
       at System.Web.Util.CalliHelper.ArglessFunctionCaller(IntPtr fp, Object o)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:
0
 
RegedekAuthor Commented:
Anyone have any ideas?
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
Tom BeckCommented:
1. Try that insert query with static values on your database directly.
2. Try adding static values in this code block to see if it goes through.
3. Try declaring your variables with their actual data types instead of just Object and with initial values, ex. Dim sql As String = String.Empty
0
 
RegedekAuthor Commented:
TommyBoy, could you explain 1 & 2 in a little more detail?  When i say I'm new to ASP .NET - I mean REALLY new (as in still quite wet behind the ears).  I apologize in advance for my ignorance.
0
 
Tom BeckCommented:
For number 1, you have an odbc connection, what is it connecting to, Access database? If so, go into Access and run the same INSERT statement with string values instead of variables in a query against your database and see if you get results.

For number 2, if just for a test, you replace all the variables in the INSERT statement with string values and run the program, do you get the same error?

Did number 3 change anything?
0
 
RegedekAuthor Commented:
I changed the sql statement to:
sql = "INSERT INTO Registrants(First_Name, Last_Name, Job_Title, Company_Name, Address, City, State, Zip_Code, Work_Phone, Fax, Registrant_Email) VALUES (' Jimmy ','Dawson','Manager','Fake Company','1234 5th Street','Anytown','CA','12345','123.456.7890','123.456.6768','mail@web.com')"
               
...And it wrote successfully to the database.
0
 
Tom BeckCommented:
Perhaps one or more of your variables are null and at least some your database fields are set to not accept null values. You can either write code to test for null values or set up all database fields to accept null values. Need help with that?
0
 
RegedekAuthor Commented:
Yes, please!
0
 
Tom BeckCommented:
Try plugging the attached code in the appropriate spot in your code. Using parameters instead of variables in your insert statements is more secure and eliminates the confusing mess of double and single quotes. Testing for null values is a little cumbersome in the attached code, but I am trying to place a default value just in case there are null values, so it won't throw an exception. BTW, your whole attempt at writing to the database should really be in a Try/Catch block.
Case "WriteNew"
                '***********


                dbconn.Open()

                sql = "INSERT INTO Customers(First_Name, Last_Name, Job_Title, Company_Name, Work_Phone, Registrant_Email) VALUES " & _
                    "(@first_name, @last_name, @job_title, @company_name, @work_phone, @registrant_email)"
                dbcomm = New OdbcCommand(sql, dbconn)
                dbcomm.Parameters.Add("@first_name", OdbcType.VarChar, 50)
                dbcomm.Parameters.Add("@last_name", OdbcType.VarChar, 50)
                dbcomm.Parameters.Add("@job_title", OdbcType.VarChar, 50)
                dbcomm.Parameters.Add("@company_name", OdbcType.VarChar, 50)
                dbcomm.Parameters.Add("@work_phone", OdbcType.VarChar, 50)
                dbcomm.Parameters.Add("@registrant_email", OdbcType.VarChar, 50)
                If Not First_Name.Text Is Nothing Then
                    dbcomm.Parameters("@first_name").value = First_Name.Text
                Else
                    dbcomm.Parameters("@first_name").value = "n/a"
                End If
                If Not Last_Name.Text Is Nothing Then
                    dbcomm.Parameters("@last_name").value = Last_Name.Text
                Else
                    dbcomm.Parameters("@last_name").value = "n/a"
                End If
                If Not Job_Title.Text Is Nothing Then
                    dbcomm.Parameters("@job_title").value = Job_Title.Text
                Else
                    dbcomm.Parameters("@job_title").value = "n/a"
                End If
                If Not Company_Name.Text Is Nothing Then
                    dbcomm.Parameters("@company_Name").value = Company_Name.Text
                Else
                    dbcomm.Parameters("@company_name").value = "n/a"
                End If
                If Not Work_Phone.Text Is Nothing Then
                    dbcomm.Parameters("@work_phone").value = Work_Phone.Text
                Else
                    dbcomm.Parameters("@work_phone").value = "n/a"
                End If
                If Not Registrant_Email.Text Is Nothing Then
                    dbcomm.Parameters("@registrant_email").value = Registrant_Email.Text
                Else
                    dbcomm.Parameters("@registrant_email").value = "n/a"
                End If
                dbcomm.ExecuteNonQuery()

                dbconn.Close()

Open in new window

0
 
RegedekAuthor Commented:
Made the changes.  Now it's telling me:
BC30451: 'First_Name' is not declared. It may be inaccessible due to its protection level.
0
 
RegedekAuthor Commented:
I should have probaly pointed out earlier that there are other forms on this .net page - I only included the code for the one form that's giving me trouble.  Maybe that will help.
Could this be why it's having trouble assigning a value to First_Name.text?
0
 
Tom BeckCommented:
If the actual forms on the real .net page are set up like the markup you posted in your question, then that's the whole problem. The variables you have in your INSERT statement do not refer to objects on the page that the code can deal with.

This is an html control: <input name="First_Name" type="text" style="width:180px;" />

In order for any reference to this control to have any meaning to the code, it needs two things: an id attribute and a runat="server" attribute. You might as well remove the "name" attribute. It's outdated and unnecessary.

The other thing I don't understand is the DataList. To access multiple controls of the same id in a DataList is not the same as accessing single, unique controls in the code.

Below is a simplified version of what you have posted in your question. All variables are accessible.
<%@ Page Language="VB" %>

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

<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.Odbc" %>
<%@ Import Namespace="System.Net.Mail" %>

<html xmlns="http://www.w3.org/1999/xhtml" >

<script language="VB" runat="server"> 
  
    Dim connStr As String = ConfigurationManager.AppSettings("DSN1").ToString()
    Dim dbconn As New OdbcConnection(connStr)
    Dim sql As Object
    Dim dbcomm As Object
    Dim dbread As Object

    Sub Page_Load()
                        
        dbconn.Open()
                
        sql = "INSERT INTO Customers(First_Name, Last_Name, Job_Title, Company_Name, Work_Phone, Registrant_Email) VALUES " & _
            "('" & First_Name.Value & "','" & Last_Name.Value & "','" & Job_Title.Value & "','" & Company_Name.Value & "','" & Work_Phone.Value & "','" & Registrant_Email.Value & "')"
        dbcomm = New OdbcCommand(sql, dbconn)
        dbcomm.ExecuteNonQuery()
                
        dbconn.Close()
                                                
        Dim sMsg As String
        sMsg += "<HTML>" & vbCrLf
        sMsg += "<BODY>" & vbCrLf
        sMsg += "New Registration Submitted:<br /><br />" & vbCrLf
        sMsg += "<table><tr><td>Registrant Name:</td><td>" & First_Name.Value & "&nbsp;" & Last_Name.Value & "</td></tr>" & vbCrLf
        sMsg += "<tr><td>Email Address:</td><td><a href='mailto:" & Registrant_Email.Value & "'>" & Registrant_Email.Value & "</a></td></tr>" & vbCrLf
        sMsg += "<tr><td>Company Name:</td><td>" & Company_Name.Value & "</td></tr>" & vbCrLf
        sMsg += "<tr><td>Work Phone:</td><td>" & Work_Phone.Value & "</td></tr></table>" & vbCrLf
        sMsg += "</BODY>" & vbCrLf
        sMsg += "</HTML>" & vbCrLf
                
        Dim objEmail As New MailMessage
        Dim Recipient As MailAddress = New MailAddress(Registrant_Email.Value)
        Dim SendBCC As MailAddress = New MailAddress("email@website.com")
        objEmail.To.Add(Recipient)
        objEmail.Bcc.Add(SendBCC)
        objEmail.From = New MailAddress("noreply@website.com")
        objEmail.Subject = "Here's the subject of the email"
        objEmail.Body = sMsg
        objEmail.IsBodyHtml = True
        Dim smtp As New SmtpClient("x.x.x.x")
        smtp.Send(objEmail)
    End Sub
</script>	
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
                  <div style="float:left;">First Name:</div>
                        <div style="float:left;"><input id="First_Name" runat="server" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Last Name:</div>
                        <div style="float:left;"><input id="Last_Name" runat="server" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Job Title:</div>
                        <div style="float:left;"><input id="Job_Title" runat="server" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Company Name:</div>
                        <div style="float:left;"><input id="Company_Name" runat="server" type="text" style="width:180px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Phone:</div>
                        <div style="float:left;"><input id="Work_Phone" runat="server" type="text" style="width:140px;" /></div>
                  </div>
                  <div>
                        <div style="float:left;">Email Address:</div>
                        <div style="float:left;"><input id="Registrant_Email" runat="server" type="text" style="width:180px;" /></div>
                  </div>
    </form>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
 
RegedekAuthor Commented:
I get it now!  
Thanks for all your help Tommy Boy!
0
 
Tom BeckCommented:
You're welcome, glad to help. I wish I had noticed it sooner.

The other thing I forgot to note is that with html controls the syntax is First_Name.Value whereas with asp:Textbox controls it's First_Name.Text.
0
 
RegedekAuthor Commented:
Good to know.  Thanks again!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.