locked
JavaScript to populate TextBox from DropDownList ***(IMPORTANT) Inside a FormView Control RRS feed

  • Question

  • User-1559458579 posted

    I am using javascript to assign values to a textbox. I love the javascript code because it does not require a postback. I want to continue to use it. Through some research I have gotten rid of the following errors:

    The name TextBox1 does not exist in the currrent context
    The name Dropdown1 does not exist in the currrent context

    The error I get now is:

    Object reference not set to an instance of an object.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    I'm hoping someone can help me clean this up and make this work within the FormView control. I'm including my code.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm5_java.aspx.cs" Inherits="echodevelopment.WebForm5_java" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <script type="text/javascript">
        function sethref() {
    
            var Textb = document.getElementById('<%= (FormView1.FindControl("FormView1").FindControl("TextBox1")).ClientID%>');
            var parLab = document.getElementById('<%= (FormView1.FindControl("FormView1").FindControl("Dropdown1")).ClientID%>').options[document.getElementById('<%= (FormView1.FindControl("FormView1").FindControl("Dropdown1")).ClientID%>').selectedIndex].text;
    
            if (parLab != '--select deptname--') {
                Textb.value = parLab
            }
    
            else {
    
                Textb.value = '';
    
            }
    
        }
    </script>
        <title></title>
        <style type="text/css">
            .auto-style1 {
                width: 500px;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
       
            <asp:FormView ID="FormView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1" Width="500px">
                <EditItemTemplate>
                   
                    <table class="auto-style1">
                        <tr>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </tr>
                    </table>
                    <br />
                    id:
                    <asp:Label ID="idLabel1" runat="server" Text='<%# Eval("id") %>' />
                    <br />
                    City:
                    <asp:TextBox ID="CityTextBox" runat="server" Text='<%# Bind("City") %>' />
                    <br />
                    Citycode:
                    <asp:DropDownList ID="Dropdown1" runat="server">
                        <asp:ListItem>--select deptname--</asp:ListItem>
                        <asp:ListItem>Test1</asp:ListItem>
                        <asp:ListItem>Test2</asp:ListItem>
                        <asp:ListItem>Test3</asp:ListItem>
                    </asp:DropDownList>
                    <br />
                    <asp:TextBox ID="TextBox1" runat="server"  ClientIDMode="Static" Text='<%# Bind("Citycode") %>'/>
                    <br />
                    <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
                    &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                </EditItemTemplate>
                <InsertItemTemplate>
                    City:
                    <asp:TextBox ID="CityTextBox" runat="server" Text='<%# Bind("City") %>' />
                    <br />
                    Citycode:
                    <asp:TextBox ID="CitycodeTextBox" runat="server" Text='<%# Bind("Citycode") %>' />
                    <br />
                    <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />
                    &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                </InsertItemTemplate>
                <ItemTemplate>
                    id:
                    <asp:Label ID="idLabel" runat="server" Text='<%# Eval("id") %>' />
                    <br />
                    City:
                    <asp:Label ID="CityLabel" runat="server" Text='<%# Bind("City") %>' />
                    <br />
                    Citycode:
                    <asp:Label ID="CitycodeLabel" runat="server" Text='<%# Bind("Citycode") %>' />
                    <br />
                    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                    <br />
                    <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
                    &nbsp;<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />
                    &nbsp;<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New" Text="New" />
                </ItemTemplate>
            </asp:FormView>
    <%--    ----------------------------------------
        -------------------------------------------%>
            
    
        </div>
            <div>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EchoConnectionString %>" DeleteCommand="DELETE FROM [Test_city] WHERE [id] = @id" InsertCommand="INSERT INTO [Test_city] ([City], [Citycode]) VALUES (@City, @Citycode)" SelectCommand="SELECT [id], [City], [Citycode] FROM [Test_city]" UpdateCommand="UPDATE [Test_city] SET [City] = @City, [Citycode] = @Citycode WHERE [id] = @id">
                    <DeleteParameters>
                        <asp:Parameter Name="id" Type="Int32" />
                    </DeleteParameters>
                    <InsertParameters>
                        <asp:Parameter Name="City" Type="String" />
                        <asp:Parameter Name="Citycode" Type="String" />
                    </InsertParameters>
                    <UpdateParameters>
                        <asp:Parameter Name="City" Type="String" />
                        <asp:Parameter Name="Citycode" Type="String" />
                        <asp:Parameter Name="id" Type="Int32" />
                    </UpdateParameters>
                </asp:SqlDataSource>
            </div>
        </form>
    </body>
    </html>
    
    
    

    Saturday, October 10, 2020 3:43 PM

All replies

  • User475983607 posted

    Your code shows a lack of fundamental knowledge that you'll need to fix.  Data bound controls have templates.  If the data bound control is in edit mode then the edit template is displayed.  Update mode -> update template. Default -> Item template.  

    Your JavaScript code is looking for edit template controls that do not exist in the item template.  This is the reason for the null reference error.  Drop the JavaScript approach it is not a good design in Web Forms for many reasons.  

    There are two ways to deal with data bound controls.  Programmatically in the code behind or through wizards and SQL Data Source controls within the markup.  You are using the wizard approach.  That's fine but you have to understand the syntax and terms to get everything working correctly otherwise it seems like magic.  It is very difficult to troubleshoot magic.

    The other big design issue with your code is the FormView expects a singe record not collection.  You can view the record, update the record, delete the record or create a new record.  Your code is tries to select may records.  You should have noticed that only the first record in the list is shown.  

    I think you'll be interested in the following doc section(s).  There's a lot of subject in the left navigation pane that you'll need to read...

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/data-access/accessing-the-database-directly-from-an-aspnet-page/inserting-updating-and-deleting-data-with-the-sqldatasource-vb

    Main section

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/data-access/

    I put together an example that might help.  It's users and colors.  You can edit a user's color, add a user color, or delete a user color.  This is not production code.  The purpose of this example is to illustrate how to handle dropdowns in a data bound control using CRUD operations.   

    CREATE TABLE Colors (
     ColorId INT PRIMARY KEY IDENTITY(1,1),
     [Name]	VARCHAR(64), 
    )
    
    INSERT INTO Colors([Name])
    VALUES ('Red'), ('Yellow'), ('Blue'), ('Green')
    
    CREATE TABLE Users (
    	UserId		INT PRIMARY KEY IDENTITY(1,1),
    	Username	VARCHAR(64)
    )
    
    INSERT INTO Users(Username)
    VALUES('Bob'), ('Sally'), ('Jane')
    
    CREATE TABLE UserColor(
    	ColorId		INT NOT NULL,
    	UserId		INT NOT NULL
    )
    
    INSERT INTO UserColor(ColorId, UserId)
    VALUES (1,1)
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="forum.aspx.cs" Inherits="WebFormsDemo.Basic.forum" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Forum Fundamentals</title>
        </head>
    <body>
        <form id="form1" runat="server">
            <asp:FormView ID="FormView1" runat="server" DataSourceID="UserColorDataSource" DataKeyNames="UserId">
                <EditItemTemplate>
                    Username:
                    <asp:DropDownList ID="UpdateUserDropDownList" runat="server" DataSourceID="UserDataSource" DataTextField="Username" DataValueField="UserId" SelectedValue='<%# Bind("UserId") %>'>
                    </asp:DropDownList>
                    <br />
                    Color:&nbsp;<asp:DropDownList ID="UpdateColorDropdownList" runat="server" DataSourceID="ColorDataSource" DataTextField="Name" DataValueField="ColorId" SelectedValue='<%# Bind("ColorId") %>'>
                    </asp:DropDownList>
                    <br />
                    <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
                    &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                </EditItemTemplate>
                <EmptyDataTemplate>
                    No data found!
                </EmptyDataTemplate>
                <InsertItemTemplate>
                    Username:
                    <asp:DropDownList ID="InserUserDropDownList" runat="server" DataSourceID="UserDataSource" DataTextField="Username" DataValueField="UserId" SelectedValue='<%# Bind("UserId") %>'>
                    </asp:DropDownList>
                    <br />
                    Color:
                    <asp:DropDownList ID="InserColorDropDownList" runat="server" DataSourceID="ColorDataSource" DataTextField="Name" DataValueField="ColorId" SelectedValue='<%# Bind("ColorId") %>'>
                    </asp:DropDownList>
                    <br />
                    <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />
                    &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                </InsertItemTemplate>
                <ItemTemplate>
                    Username:
                    <asp:Label ID="UsernameLabel" runat="server" Text='<%# Bind("Username") %>' />
                    <br />
                    Name:
                    <asp:Label ID="NameLabel" runat="server" Text='<%# Bind("Name") %>' />
                    <br />
                    <asp:HiddenField ID="DeleteUserId" runat="server" Value='<%# Bind("UserId") %>' />
    
                    <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
                    &nbsp;<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />
                    &nbsp;<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New" Text="New" />
                </ItemTemplate>
            </asp:FormView>
            <asp:SqlDataSource ID="UserColorDataSource" runat="server" 
                ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" 
                DeleteCommand="DELETE UserColor
    WHERE UserId = @UserId"
                InsertCommand="INSERT INTO UserColor(ColorId, UserId)
    VALUES (@ColorId, @UserId)" 
                SelectCommand="SELECT uc.UserId, u.Username, uc.ColorId, c.[Name]
    FROM UserColor AS uc 
    	JOIN Users AS u ON u.UserId = uc.UserId
    	JOIN Colors AS c ON c.ColorId = uc.ColorId
    WHERE u.UserId = @UserId"
                UpdateCommand="UPDATE UserColor
    SET ColorId = @ColorId
    WHERE UserId = @UserId">
                <DeleteParameters>
                    <asp:Parameter Name="UserId" Type="Int32" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:FormParameter Name="UserId" FormField="InserUserDropDownList" Type="Int32"  />
                    <asp:FormParameter Name="ColorId" FormField="InsertColorDropDownList" Type="Int32" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:QueryStringParameter Name="UserId" QueryStringField="UserId" Type="Int32" DefaultValue="1" />
                    <asp:FormParameter Name="ColorId" FormField="UpdateColorDropDownList" Type="Int32"/>
                </UpdateParameters> 
                <SelectParameters>
                    <asp:QueryStringParameter Name="UserId" QueryStringField="UserId" DefaultValue="1" Type="Int32" />
                </SelectParameters>
            </asp:SqlDataSource>
            <asp:SqlDataSource ID="UserDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [UserId], [Username] FROM [Users]"></asp:SqlDataSource>
            <asp:SqlDataSource ID="ColorDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [ColorId], [Name] FROM [Colors]"></asp:SqlDataSource>
        </form>
    </body>
    </html>
    

    Saturday, October 10, 2020 9:25 PM
  • User-1559458579 posted

    I am very aware I don't have the fundamental knowledge. I don't think I would be here if I had the FUNDAMENTAL KNOWLEDGE @MGEBHARD!

    Sunday, October 11, 2020 12:00 PM
  • User-1559458579 posted

    The formview has absolutely no issues running running CRUD operations. The CRUD operations were automatically generated by the Visual Studio Wizard and, they work. I paid a developer to solve the javascript and it's working fine now. Closing this out.

    Sunday, October 11, 2020 12:08 PM