Solved

ASP/VB .Net Text Box Not Populating

Posted on 2009-05-20
5
303 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
ID: 24435616
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
ID: 24436372
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
ID: 24436722
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
ID: 24445122
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
ID: 31583675
I appreciate your patience and the extra effort you put in. Thanks again!
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

815 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

8 Experts available now in Live!

Get 1:1 Help Now