Filling TextBoxes from an ASP.NET DropDownList SelectedIndexChange

in #utopian-io8 years ago (edited)

What Will I Learn?

  • You will learn Filling TextBoxes with Java Script on DropDownList SelectedIndexChange
  • You will learn Creating a JavaScript Array Dynamically at Runtime

Requirements

ASP.NET Core

Difficulty

Intermediate

Tutorial Contents

  1. Creating a JavaScript Array in Code
  2. Output form GetFiveRowsAllColumnsArray
  3. JavaScript to Fill the First Name Text Boxes

Filling TextBoxes from an ASP.NET DropDownList SelectedIndexChange

How do I fill TextBoxes from an ASP.NET DropDownList SelectedIndexChange?  Sometimes you wish you could get completely away from JavaScript, but at the same time a little ingenuity and work will greatly improve the responsivness of your ASP.NET Application.  JavaScript can be a real pain; either you get it exactly right or it will not work.

In an application I am working on, the page is basically a Wizard with several steps, three of which need to fill a set of 5 TextBoxes when the user selects a value from a DropDownList located above the TextBoxes.  I started doing this, but obviously, that requires a PostBack to the Server and results in page refresh.  The neat thing is that it can be done with JavaScript and eliminate both the PostBack and the trip to the server.  This tutorial will show all of the code required to accomplish this trick.

For this application, I am importing first name, last name, and phone number from a text/csv file.  However, the DropDownList can contain the three fields in any order.  So I have to let the user tell me which field is which.  I then record the index of the DropDownList after the selection.  In addition, I fill up to 5 text boxes with the corresponding field from the input file.  First, I need to build, a two dimensional array and save it to the page in a Literal control.  From then on the array will be persisted in ViewState by the Literal control.  This is done by calling the method shown below.  

Creating a JavaScript Array in Code

/// <summary>
/// Return string of a javascript matrix[numFields, 5] 
/// </summary>
/// <returns>string</returns>
private string GetFiveRowsAllColumnsArray()
{
    bool headerExtant = (VSHdrYesNo == "Yes");
    string patt = VSParsePattern;

    StreamReader sr = new StreamReader(VSFileName);

    int linesRead = 0;
    int numFields = 0;

    string line = sr.ReadLine();
    string[] lineArray;
    string[,] allFields;

    // read one line to get the number of fields to dimension the array
    if (line != null && line.Trim().Length > 0 && linesRead < 5)<BR>     {
        // if header not present, close the file and reopen to get back
        // ready to read the first line of data
        if (!headerExtant)
        {
            sr.Close();
            sr = new StreamReader(VSFileName);
        } // if

        Match m = Regex.Match(line, patt, RegexOptions.ExplicitCapture);

        if (!m.Success)
        {
            throw new Exception("Parsing error with regex in GetFiveRowsAllColumnsArray.");
        } // if

        numFields = m.Groups["field"].Captures.Count;

        allFields = new string[numFields, 5];

        // initialize all fields to ""
        for (int y = 0; y < 5; y++)<BR>         {
            for (int x = 0; x < numFields; x++)<BR>             {
                allFields[x, y] = string.Empty;
            } // for
         } // for

    } // if     
    else
    {
        return null; // file has no rows
    } // else

    linesRead = 0;

    // array is dimensioned, populate it
    for (int y = 0; y < 5; y++)<BR>     {
        while (linesRead <= 5)<BR>         {
            line = sr.ReadLine();
            if (line == null)
            {
                break;
            } // if
            else if (line.Trim().Length < 1)<BR>             {
                continue;
            } // else

            linesRead++;
            break;
        }

        if (line == null)
        {
            break;
        }

        Match m = Regex.Match(line, patt, RegexOptions.ExplicitCapture);

        if (!m.Success)
        {
            throw new Exception("Parsing error with regex");
        } // if

        lineArray = new string[m.Groups["field"].Captures.Count];

        for (int x = 0; x < numFields; x++)<BR>         {
            allFields[x, y] = 
                m.Groups["field"].Captures[x].Value.Replace("\"", "").Trim();
        }
    } // for

    // we have the initial array, build the javascript matrix array
    StringBuilder sb = new StringBuilder(2000);

    sb.Append("" + Environment.NewLine);

    return sb.ToString(); // change to return the string
} // method: GetFiveRowsAllColumnsArray



The output from this method will be a string containing a JavaScript Array as shown below:

Output form GetFiveRowsAllColumnsArray.

<script type="text/javascript">
(html comment removed: 
var matrix = new Array(3);
matrix[0] = new Array(5);
matrix[0][0] = "Josh";
matrix[0][1] = "Sally";
matrix[0][2] = "Adam";
matrix[0][3] = "";
matrix[0][4] = "";
matrix[1] = new Array(5);
matrix[1][0] = "Jones, Jr";
matrix[1][1] = "Jones";
matrix[1][2] = "Doe Jr";
matrix[1][3] = "";
matrix[1][4] = "";
matrix[2] = new Array(5);
matrix[2][0] = "8633135544";
matrix[2][1] = "8633135542";
matrix[2][2] = "86433135549";
matrix[2][3] = "";
matrix[2][4] = "";
// )
</script>


This string will be saved in an ASP.NET Literal Control, which will make the "matrix" array accessible to JavaScript Functions called to fill the text boxes.  The JavaScript, will be saved in script file and a reference to the file will be placed in the ASPX page.  The function shown below fills only the text boxes related to first names.  The JS for the last name and phone number would be essentially the same with only the names of the controls being changed.

JavaScript to Fill the First Name Text Boxes

function FillFNTextBoxes(sender)
{
    var pre = sender.id.replace("ddlFirstNames", "");
    
    var FName = document.getElementById(pre + "ddlFirstNames");
    var idx = Number(FName.selectedIndex);
    
    var T1 = document.getElementById(pre + "txtSampleFN1");
    var T2 = document.getElementById(pre + "txtSampleFN2");
    var T3 = document.getElementById(pre + "txtSampleFN3");
    var T4 = document.getElementById(pre + "txtSampleFN4");
    var T5 = document.getElementById(pre + "txtSampleFN5");
    
    if(idx > 0)
    {
        T1.value = matrix[idx - 1][0];
        T2.value = matrix[idx - 1][1];
        T3.value = matrix[idx - 1][2];
        T4.value = matrix[idx - 1][3];
        T5.value = matrix[idx - 1][4];
        // so we don't hit the server, however there is
        // no code involved on the dropdownlist chang        
        return false; 
    }
}


In the Page_Load event, I will set the attributes of the DropDownLists to have a "onchange" event that will call the JaveScript event of the respective DDL into the ASPX page with the following code.

ddlFirstNames.Attributes.Add("onChange", "return FillFNTextBoxes(this);");
ddlLastNames.Attributes.Add("onChange", "return FillLNTextBoxes(this);");
ddlPhoneNumbers.Attributes.Add("onChange", "return FillPNTextBoxes(this);");

When the user makes a selection from the respective DropDownList, the JavaScript function associated with that list is called by the "onchange" event.  



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

A good lesson to learn javascrift. I am happy to know that you are a web designer.

@gaultier, Approve is not my ability, but I can upvote you.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @gaultier I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.094
BTC 63573.30
ETH 1778.51
USDT 1.00
SBD 0.39