Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

ASP/VB .Net Text Box Not Populating

Posted on 2009-05-20
5
Medium Priority
?
322 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

597 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