Solved

ASP/VB .Net Text Box Not Populating

Posted on 2009-05-20
5
295 Views
Last Modified: 2012-06-22
I have a SQL Table with the following fields: Dept Name, Dept, and Contacts. On the form, when a person selects the Dept Name it should automatically populate the corresponding contact into a textbox on the form, but it isn't firing. Further, It doesn't appear to be picking up anything because it's the only info that's not going into the table.
ASP Drop Down:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" AutoPostBack="True" DataSourceID="SqlDataSource3"

 DataTextField="DeptName" DataValueField="Dept" > </asp:DropDownList>
 

VB.net:

  Protected Sub DropDownList1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.DataBound

        DropDownList1.Items.Insert(0, New ListItem("Select One", ""))
 

        intcount = 0

        Dim sConn As Data.SqlClient.SqlConnection

        Dim sComm As Data.SqlClient.SqlCommand

        Dim sAdapt As Data.SqlClient.SqlDataAdapter
 

        sConn = New Data.SqlClient.SqlConnection("server=server1;database=dbase;UID=useID;PWD=pass")

        sComm = New Data.SqlClient.SqlCommand("SELECT Contacts From database where Dept = '" & DropDownList1.SelectedItem.Text & "'", sConn)

        sAdapt = New Data.SqlClient.SqlDataAdapter(sComm)

        sConn.Open()
 

        Dim r As Data.SqlClient.SqlDataReader = sComm.ExecuteReader()

        While r.Read()

            Dim strEmail As String = CStr(r("Contacts"))

            TextBox5.Text = strEmail

        End While

        r.Close()
 

        If DropDownList1.SelectedItem.Text = "Select One" Then

            TextBox5.Text = ""

        End If
 

        Image2.Visible = False

        Image3.Visible = False

        Label10.Visible = False

        Label10.Text = ""

    End Sub
 

    Public Sub Add_SQL()

        Dim sConn As Data.SqlClient.SqlConnection

        Dim sComm As Data.SqlClient.SqlCommand

        Dim sAdapt As Data.SqlClient.SqlDataAdapter
 

        sConn = New Data.SqlClient.SqlConnection("server=server1;database=dbase;UID=useID;PWD=pass")

        sComm = New Data.SqlClient.SqlCommand("INSERT INTO autodatabase

(Contractor, FN, MI, LN, Requestor, Submitted, Contacts) VALUES ('" & DropDownList1.SelectedItem.Text & "','" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & strUser & "','" & strDate & "','" & TextBox5.Text & "')", sConn)

        sAdapt = New Data.SqlClient.SqlDataAdapter(sComm)

        sConn.Open()

        sComm.ExecuteNonQuery()

        sConn.Close()
 

    End Sub

End Class

Open in new window

0
Comment
Question by:JB4375
  • 3
  • 2
5 Comments
 
LVL 12

Expert Comment

by:wht1986
Comment Utility
You want to fetch the values on select index changed, not on the data bound event

On my page I would include the default item in the markup and bind on page load like:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"
    AutoPostBack="true"
    DataTextField="DeptName" DataValueField="Dept"
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="Select One" Value="" />
</asp:DropDownList>

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.DropDownList1.DataSource = YourDataSource;
        this.DropDownList1.DataBind();
    }
}

then get your contacts from the  selected index changed event

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Now query your database to get the contacts here
}

May I also suggest using parameters in your sql statement

sComm = new SqlCommand("SELECT Contacts From database where Dept=@DEPT", sConn)
sComm.Parameters.AddWithValue("@DEPT", this.DropDownList1.SelectedValue);
0
 
LVL 1

Author Comment

by:JB4375
Comment Utility
OK.... I'm floored.... I'm actually just trying to clean up a page where the last programmer put "Select One" as the top entry of the SQL table. Didn't take it would take so much to get the option in the DDL.
Ok... I've edited the drop down on the ASP. Am I correct in assuming that the rest of the code you've provided is for the VB page?
If so I have a Protected Sub Page Load, listed below, where I pull in the Authorized User in order to submit it to the SQL table. How would the code you've provided below work in relation to that? Assuming it will.
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.DropDownList1.DataSource = YourDataSource;
        this.DropDownList1.DataBind();
    }
}
 
 Using parameters within the SQL statement...Is that for the Sub that handles the drop down, Add SQL, or both?
Thanks in advance.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        strDate = Now

        strUser = (Request.ServerVariables("AUTH_USER"))
 

        If InStr(strUser, "domain\") Then

            strUser = Replace(strUser, "domain\", "")

        End If

        If InStr(strUser, "domain\") Then

            strUser = Replace(strUser, "domain\", "")

        End If

        Label9.Text = "medctr\" & strUser
 

    End Sub

Open in new window

0
 
LVL 12

Accepted Solution

by:
wht1986 earned 500 total points
Comment Utility
Ok without knowing your page layout, Im going to make mine own up.  The page below has a dropdown for selecting the department, a textbox for the contact of that department, and a button to add the item in the textbox to another table.  My 2 tables are shown below in the pictures.

This code does what your original question asked. "How to fill a textbox based on a value choosen from a dropdownlist"  You should be able to use this is a a basis for applying to your exact page.

If you need more help than this, provide the database schema and html markup of the page.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_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></title>

</head>

<body>

    <form id="form1" runat="server">

        <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataTextField="DeptName" DataValueField="Dept" onselectedindexchanged="DropDownList1_SelectedIndexChanged" DataSourceID="SqlDataSource1">

            <asp:ListItem Text="Select One" Value="" />

        </asp:DropDownList>

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:Button ID="Button1" runat="server" Text="Button" />

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PMr3ConnectionString %>" SelectCommand="SELECT * FROM [Departments]"></asp:SqlDataSource>

    </form>

</body>

</html>
 

=========================
 

Imports System.Data.SqlClient
 

Partial Class _Default

    Inherits System.Web.UI.Page
 

    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged

        If DropDownList1.SelectedIndex = 0 Then

            TextBox1.Text = ""

        Else

            Dim connStr As String = ConfigurationManager.ConnectionStrings("PMr3ConnectionString").ConnectionString

            Dim conn As SqlConnection = New SqlConnection(connStr)

            Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Departments WHERE Dept=@DEPT", conn)

            cmd.Parameters.AddWithValue("@DEPT", CInt(DropDownList1.SelectedValue))

            conn.Open()

            Dim rdr As SqlDataReader = cmd.ExecuteReader()

            If rdr.Read() Then

                TextBox1.Text = rdr.GetString(2)

            End If

            rdr.Close()

            conn.Close()

        End If

    End Sub
 

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim connStr As String = ConfigurationManager.ConnectionStrings("PMr3ConnectionString").ConnectionString

        Dim conn As SqlConnection = New SqlConnection(connStr)

        Dim cmd As SqlCommand = New SqlCommand("INSERT INTO AddStore (ContactName, Requestor) VALUES (@CONTACTNAME, @REQUESTOR)", conn)

        cmd.Parameters.AddWithValue("@CONTACTNAME", TextBox1.Text)

        cmd.Parameters.AddWithValue("@REQUESTOR", Page.User.Identity.Name)

        conn.Open()

        cmd.ExecuteNonQuery()

        conn.Close()

    End Sub
 

End Class

Open in new window

Capture.JPG
Capture1.JPG
0
 
LVL 1

Author Comment

by:JB4375
Comment Utility
That did it!! I actually only had to make the suggested change at the DDL on the ASP, and the changing the VB protected sub from this:
Protected Sub DropDownList1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.DataBound
        DropDownList1.Items.Insert(0, New ListItem("Select One", ""))
To this:
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex = 0 Then
TextBox1.Text = ""
Else
Thanks again!!
 
0
 
LVL 1

Author Closing Comment

by:JB4375
Comment Utility
I appreciate your patience and the extra effort you put in. Thanks again!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now