Solved

How do I assign the value of textbox to dropdownlist????

Posted on 2013-02-03
11
406 Views
Last Modified: 2013-04-04
This issue has driven me nuts for a whole day.

I have a dropdownlist in gridview with 3 options, one of those options is "Other"

If a user selects "Other" from the dropdown, a textbox with ID="txtOther" is enabled.

By enabling it, a user can type in whatever value s/he in the textbox.

I am able to enable textbox when "Other" is selected from dropdownlist.

The problem that I am having problems figuring out is  how to assign the value of textbox to the dropdown.

For instance, the dropdownlist ID is txtEmployer and the database fieldname for this dropdownlist is Employer.

So, if I select Risk from the dropdownlist and insert into the db, the value is stored in Employer field.

If the user selects "Other" from the dropdownlist, and and the textbox is enabled, I want the value inserted into this box to be stored in the Employer fieldname.

So far, it isn't working.\

For instance, if I insert "Testing" into the textbox, when I debug the code, it inserts a numeric value instead of the text I entered.

I must mention that there is another dropdownlist for selecting users Name called txtLoginName and the db fieldname for this is called Login_Id which is an integer field.

So, it seems to me that the value of login_Id is also getting inserted into the txtEmployer dropdown whenever I type into the textbox.

Any ideas how to fix this?

I hope my issue is clear.

Here is the relevant code I have so far:

'Markup
                    <asp:TemplateField HeaderText="Employer">
                        <ItemTemplate>
                            <asp:DropDownList ID="txtEmployer" runat="server" AutoPostBack="true" OnSelectedIndexChanged="SelectedIndexChanged">
                                <asp:ListItem>Select</asp:ListItem>
                                <asp:ListItem Value="AllScripts">AllScripts</asp:ListItem>
                                <asp:ListItem Value="Contractor">Contractor</asp:ListItem>
                                <asp:ListItem Value="Other">Other</asp:ListItem>
                           </asp:DropDownList>
                             <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txtEmployer"
                                ErrorMessage="*" InitialValue="Select"></asp:RequiredFieldValidator>
                        </ItemTemplate>
                         </asp:TemplateField>
                        <asp:TemplateField HeaderText="Other">
                        <ItemTemplate>
                               <asp:TextBox ID="txtOther" runat="server" TabIndex="435"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtOther"
                                ErrorMessage="*" SetFocusOnError="True"></asp:RequiredFieldValidator>
                        </ItemTemplate>
                        </asp:TemplateField>

Open in new window


   
'Code behind
 Public Sub SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim dropDownList As DropDownList = DirectCast(sender, DropDownList)
        Dim txtOther As TextBox = TryCast(dropDownList.Parent.FindControl("txtOther"), TextBox)
        If dropDownList.SelectedValue = "Other" Then
            txtOther.Visible = True
            grvStudentDetails.Columns(7).Visible = True
            TryCast(dropDownList.FindControl("txtOther"), TextBox).Text = txtOther.Text

        Else
            txtOther.Visible = False
            grvStudentDetails.Columns(7).Visible = False
        End If

        ' Dim ddr As DropDownList = DirectCast(sender, DropDownList)

        'Dim row As GridViewRow = DirectCast(ddr.NamingContainer, GridViewRow)

        'Dim row As GridViewRow = DirectCast(ddr.NamingContainer, GridViewRow)
        'TryCast(row.FindControl("txtOther"), TextBox).Enabled = (dropDownList.SelectedValue = "Other")
        'If dropDownList.SelectedValue = "Select" Then
        'TryCast(row.FindControl("txtNewUser"), TextBox).Text = txtNewUser.Text
        'End If
    End Sub

Open in new window

0
Comment
Question by:sammySeltzer
11 Comments
 
LVL 20

Expert Comment

by:informaniac
Comment Utility
Please show code to save the data
0
 
LVL 28

Author Comment

by:sammySeltzer
Comment Utility
Here it is. Sorry, I stepped out for a second.

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Try
        SetRowData()
        Dim table As DataTable = TryCast(ViewState("CurrentTable"), DataTable)

        If table IsNot Nothing Then
            For Each row As DataRow In table.Rows
                Dim txLName As String = TryCast(row.ItemArray(1), String)
                Dim txName As String = TryCast(row.ItemArray(2), String)
                Dim txEmail As String = TryCast(row.ItemArray(3), String)
                Dim txRole As String = TryCast(row.ItemArray(4), String)
                Dim txPhone As String = TryCast(row.ItemArray(5), String)
                Dim drpEmpl As String = TryCast(row.ItemArray(6), String)
                Dim txVIP As String = TryCast(row.ItemArray(7), String)
                Dim drpLCB As String = TryCast(row.ItemArray(8), String)


                'Dim ddl As DropDownList = DirectCast(sender, DropDownList)
                'Dim txtNewUser As TextBox = TryCast(ddl.FindControl("txtNewUser"), TextBox)
                'If txtNewUser IsNot Nothing AndAlso ddl IsNot Nothing Then
                'add new listitem here
                'Dim customItem As New ListItem(txtNewUser.Text, txtNewUser.Text)
                'ddl.Items.Add(customItem)
                'End If

                '    Dim ddlvalue As String = ""
                'Dim idx As Integer = grvStudentDetails.EditIndex

                'If drpEmpl = "Other" Then
                'ddlvalue = DirectCast(grvStudentDetails.FindControl("txtOther"), TextBox).Text

                '   Else
                '      ddlvalue = drpEmpl
                'End If


                If txLName IsNot Nothing OrElse txLName IsNot Nothing OrElse txEmail IsNot Nothing OrElse txRole IsNot Nothing OrElse txPhone IsNot Nothing OrElse drpEmpl IsNot Nothing OrElse txVIP IsNot Nothing OrElse drpLCB IsNot Nothing Then

                    Try
                    Dim dateentered As String = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
                    'Response.Write(dateentered)
                    'Response.End()

                    Dim s As String
                    Dim count As Integer

                    'If LoginName already exists, alert user
                    s = "SELECT Count(*) FROM Employee_Roster WHERE login_id = " & txLName
                    'Response.Write(s)
                    'Response.End()
                    Dim connSt As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
                    Dim connc As New OleDbConnection(connSt)
                    Dim cmdc As New OleDbCommand(s, connc)
                    'cmdc.Parameters.AddWithValue("login_id", txtLoginName.SelectedValue)
                    connc.Open()
                    ' cmdc.ExecuteNonQuery()
                    count = cmdc.ExecuteScalar()


                    '   Now let's see if we found existing record
                    If count > 0 Then
                        'Display some feedback to the user to let them know it was processed
                        lblResult.ForeColor = System.Drawing.Color.Green
                        lblResult.Text = "User already is in the Excel Sheet!"
                    Else
                        s = "INSERT INTO Employee_Roster(login_id, FullName, Email_Address, Role_Dept,Phone,Employer,VP,entryDate,Notes) VALUES "
                        s += "('" & txLName & "', '" & txName & "', '" & txEmail & "', '" & txRole & "', '" & txPhone & "', '" & drpEmpl& "','" & txVIP & "','" & dateentered & "', '" & drpLCB & "')"
                        Response.Write(s)
                        Response.End()
                        Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
                        Dim conn As New OleDbConnection(connStr)
                        Dim cmd As New OleDbCommand(s, conn)
                        conn.Open()
                        cmd.ExecuteNonQuery()
                        conn.Close()


                        'Display some feedback to the user to let them know it was processed
                        lblResult.ForeColor = System.Drawing.Color.Green
                        lblResult.Text = "Record successfully saved!"

                        'Clear the form
                        txLName = ""
                        txLName = ""
                        txEmail = ""
                        txRole = ""
                        txPhone = ""
                        txVIP = ""
                    End If
                     Catch

                    'If the message failed at some point, let the user know
                    lblResult.ForeColor = System.Drawing.Color.Red
                    lblResult.Text = "Your record failed to save, please try again."

                     End Try

                End If
            Next
        End If
         Catch ex As Exception
        Throw New Exception(ex.Message)
         End Try
    End Sub

Open in new window


drpEmpl is the txtEmployer dropdownlist and txLName is the txtLoginName dropdownlist.

That's the one where the numeric value populates both dropdownlists.
0
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
Where is the code that deals with this txtOther textbox?
0
 
LVL 26

Expert Comment

by:Alan Warren
Comment Utility
Being an unbound dropdownlist it should be no problem to add new items. The added items will be persisted through postback events, but will be lost if the page is loaded afresh or navigated away from.

Have a look at this sample:
Choose 'Other' from the dropdown, then type some text in the  textbox and hit [Enter].
<%@ Page Language="VB" %>

<!DOCTYPE html>

<script runat="server">

    Protected Sub txtOther_TextChanged(sender As Object, e As EventArgs)
        txtEmployer.Items.Add(sender.text)
        txtEmployer.SelectedValue = sender.text
        sender.visible = False
    End Sub

    Protected Sub txtEmployer_SelectedIndexChanged(sender As Object, e As EventArgs)
        If sender.SelectedValue = "Other" Then
            txtOther.Visible = True
            txtOther.Focus()
        End If
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="txtEmployer" runat="server" AutoPostBack="true" OnSelectedIndexChanged="txtEmployer_SelectedIndexChanged" >
        <asp:ListItem>Select</asp:ListItem>
        <asp:ListItem Value="AllScripts">AllScripts</asp:ListItem>
        <asp:ListItem Value="Contractor">Contractor</asp:ListItem>
        <asp:ListItem Value="Other">Other</asp:ListItem>
    </asp:DropDownList>
    <asp:TextBox ID="txtOther" runat="server" TabIndex="435" OnTextChanged="txtOther_TextChanged" Visible="false" />
    </div>
    </form>
</body>
</html>

Open in new window

Alan
0
 
LVL 28

Author Comment

by:sammySeltzer
Comment Utility
I am able to accomplish this using similar approach.

My issue is I am doing this with gridview.

That's the issue.

How do I accomplish same using gridview.

If you can give a working example of how to do it with gridview dropdownlist an textbox, then I can easily assign the points and grade.

Thanks for your help.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 26

Expert Comment

by:Alan Warren
Comment Utility
Hi Sammy,
give this a try, you will have to define a connection string, probably the same as your Gridview connection string would do the trick.
<%@ Page Language="VB" %>

<!DOCTYPE html>

<script runat="server">

    Protected Sub txtEmployer_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim objTextBox As TextBox = Nothing
        objTextBox = CType(sender.NamingContainer.FindControl("txtOther"), TextBox)
        If objTextBox IsNot Nothing Then
            With objTextBox
                .Visible = True
                .Focus()
            End With
        End If
    End Sub

    Protected Sub txtOther_TextChanged(sender As Object, e As EventArgs)
        Dim objDropDownList As DropDownList = Nothing
        objDropDownList = CType(sender.NamingContainer.FindControl("txtEmployer"), DropDownList)
        If objDropDownList IsNot Nothing Then
            With objDropDownList
                .Items.Add(sender.text)
                .SelectedValue = sender.text
                .Focus()
                sender.visible = False
            End With
        End If
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
            <asp:TemplateField HeaderText="Employers">
                <ItemTemplate>
                    <asp:DropDownList ID="txtEmployer" runat="server" AutoPostBack="true" OnSelectedIndexChanged="txtEmployer_SelectedIndexChanged" >
                        <asp:ListItem>Select</asp:ListItem>
                        <asp:ListItem Value="AllScripts">AllScripts</asp:ListItem>
                        <asp:ListItem Value="Contractor">Contractor</asp:ListItem>
                        <asp:ListItem Value="Other">Other</asp:ListItem>
                    </asp:DropDownList>
                    <asp:TextBox ID="txtOther" runat="server" TabIndex="435" Visible="false" OnTextChanged="txtOther_TextChanged" />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="select 1 as ID union all select 2 union all select 3" ConnectionString="<%$ ConnectionStrings:cnYourConnection %>"></asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Open in new window

Alan
0
 
LVL 28

Author Comment

by:sammySeltzer
Comment Utility
Sorry, I forgot to say that I was able to get this far with gridview.

Issue is with adding the records to the database.

If dropdownlist ="Other" then insert textbox record

else
insert dropdownlist option

end if.

There is where there is an issue.
0
 
LVL 26

Expert Comment

by:Alan Warren
Comment Utility
Hi Sammy,
Do you have a connection name defined in your web.config, if so what is it?
Could I know:
  the name of the table into which we shall add the value of the textbox?
  the name of the field in the target table into which we shall add the value?
  the type of database we are dealing with and version if applicable?

Alan
p.s. your dropdownlist is unbound, so inserting the value into a table field won't change the items in the dropdownlist, it would first need to bound to a datasource that is populated from the items in the target table; we would then need to invoke databind on the bound dropdownlist after successfully inserting a new item.
0
 
LVL 28

Author Comment

by:sammySeltzer
Comment Utility
Hi,

The name is criptsConnstring.

Tablename is Rosters although you could use any name you wish and I can model mine after that.
0
 
LVL 26

Accepted Solution

by:
Alan Warren earned 500 total points
Comment Utility
Sammy,
is it a SQL DB or an Access DB?
If Access, I need the flavor (different providers for different versions).
If it's SQL something like this will insert a record:
    Protected Sub txtOther_TextChanged(sender As Object, e As EventArgs)
        
        Dim strSql As String = "INSERT INTO Table_1 (Filename) VALUES('" & sender.Text & "')"
        ' Create Instance of Connection and Command Object
        Using myConnection As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("criptsConnstring").ConnectionString)
            Using myCommand As New System.Data.SqlClient.SqlCommand(strSql, myConnection)

                ' Mark the Command as a Text
                myCommand.CommandType = System.Data.CommandType.Text

                Try
                    ' Open the connection
                    myConnection.Open()

                    ' Execute the SQL
                    myCommand.ExecuteNonQuery()


                Catch SQLexc As System.Data.SqlClient.SqlException
                    'strErrMsg = SQLexc.ToString
                    'GoTo ReportError
                End Try

            End Using
        End Using
        
        'Dim objDropDownList As DropDownList = Nothing
        'objDropDownList = CType(sender.NamingContainer.FindControl("txtEmployer"), DropDownList)
        'If objDropDownList IsNot Nothing Then
        '    With objDropDownList
        '        .Items.Add(sender.text)
        '        .SelectedValue = sender.text
        '        .Focus()
        '        sender.visible = False
        '    End With
        'End If
    End Sub

Open in new window

Need to update the Text_Changed() Event

Alan
0
 
LVL 28

Author Comment

by:sammySeltzer
Comment Utility
Alan,

I see where you are going with this.

According to your design, display all exsiting records, then add aditional records.

But 2 issues with this approach.

1, what if no record exists?

We would rather present an insert screen and a user select the option s/he wants to insert.

2, I can't even get the screen to display anything unless I select records from the db first.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

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 …
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
This video discusses moving either the default database or any database to a new volume.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

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

10 Experts available now in Live!

Get 1:1 Help Now