Handy Drop Down List Utilities

Using DropDownLists is so common I’ve created a few utilities you may find useful.

The general pattern is to add a method to your classes which returns a dictionary<string, string> of key and value pairs and then use that method to fill dropdownlists on your page, set defaults, select values etc.

Here is an example method FindKeyItems from a class called Location that creates a dictionary using the classes database key LocationID as the dropdown list value and Description as the text to display.

 
///
<summary>
/// Returns list of Location key value (LocationID,Description) pairs as a dictionary object
/// </summary>
/// <returns></returns>
public static Dictionary<string, string> FindKeyItems()
{

    Database D = DatabaseFactory.CreateDatabase(“CIMS”);
    string sql = “Select LocationID, Description from tblLocation order by LocationID”;
    DbCommand cmd = D.GetSqlStringCommand(sql);
    IDataReader IDR = D.ExecuteReader(cmd);
    Dictionary<string, string> Dict = new Dictionary<string, string>();

    while (IDR.Read())
    {
        Dict.Add(IDR.GetValue(0).ToString(), IDR.GetValue(1).ToString());
    }

    return Dict;
}

The following method populates a dropdown list:

///
<summary>
/// Populates a dropdown list
/// </summary>
/// <param name=”D”>Dropdown list to populate</param>
/// <param name=”Dict”>Dictionary of key/value pairs</param>
/// <param name=”DefaultText”>Text to insert as first item e.g. SELECT ONE. Enter empty string to ignore</param>
/// <param name=”SelectedValue”>ID/Key of item to select by default. Enter empty string to ignore</param>
public static void FillDropDownList(DropDownList D, Dictionary<string, string> Dict, string DefaultText, string SelectedValue)
{
    D.Items.Clear();

    if (DefaultText != “”) { D.Items.Add(new ListItem(DefaultText, “0″)); }

    foreach (KeyValuePair<string, string> KVP in Dict)
    {
        D.Items.Add(
new ListItem(KVP.Value, KVP.Key));
    }

    ListItem LI = D.Items.FindByValue(SelectedValue);
    if (LI != null) { D.Items.FindByValue(SelectedValue).Selected = true; }
}

This overloaded method populates a dropdownlist and sets the default selected item using the text value instead:

///
<summary>
/// Populates a dropdown box and selects an item by text value (instead of ID)
/// </summary>
/// <param name=”D”>Dropdown list to populate</param>
/// <param name=”Dict”>Dictionary of key/value pairs</param>
/// <param name=”DefaultText”>Text to insert as first item e.g. SELECT ONE. Enter empty string to ignore</param>
/// <param name=”SelectedText”>Text value of item to select once populated</param>
public static void FillDropDownListAndSelectItemByText(DropDownList D, Dictionary<string, string> Dict, string DefaultText, string SelectedText)
{
    FillDropDownList(D, Dict, DefaultText,
“”);
    dropDownSelectItemByText(D, SelectedText);
}

Here is the code for dropDownSelectItemByText:

///
<summary>
/// Selects Item in dropdown matching selected text. Does nothing when item not found.
/// </summary>
/// <param name=”D”></param>
/// <param name=”SelectedValue”></param>
public static void dropDownSelectItemByText(DropDownList D, string SelectedText)
{
    ListItem LI =
new ListItem();
    LI = D.Items.FindByText(SelectedText);

    if (LI != null)
    {
        D.SelectedItem.Selected =
false;
        D.Items.FindByText(SelectedText).Selected =
true;
    }
}

Here is a method for finding an item by value:

///
<summary>
/// Selects Item in dropdown matching selected value. Does nothing when item not found.
/// </summary>
/// <param name=”D”></param>
/// <param name=”SelectedValue”></param>
public static void dropDownSelectItemByValue(DropDownList D, string SelectedValue)
{
    ListItem LI =
new ListItem();
    LI = D.Items.FindByValue(SelectedValue);

    if (LI != null)
    {
        D.SelectedItem.Selected =
false;
        D.Items.FindByValue(SelectedValue).Selected =
true; }} Here is an example for a TRUE/FALSE list, in case you’re too lazy to just type it into the page <grin>:
public
static void FillTrueFalseDropDownList(DropDownList D, string DefaultText, string SelectedValue)
{

    Dictionary<string, string> Dict = new Dictionary<string, string>();
    Dict.Add(
“True”, “True”);
    Dict.Add(
“False”, “False”);
    FillDropDownList(D, Dict, DefaultText, SelectedValue);

}

That completes my list of dropDownList utilities!

 

- The Guru

 

Utilities to add Mouseover Highlighting to a GridView

The following utilities support adding mouseover highlighting so the user gets a visual indication of the row the mouse is over. The first just highlights the row while the second also enables clicking on the row to redirect to another page.

 

To Add Mouseover Highlighting, place the following code in a utility class:

public static void AddMouseoverHighlight(GridViewRowEventArgs e, string HighlightColor, string NormalRowColor, string AlternateRowColor)

{

    if (e.Row.DataItemIndex > -1)

    {

        e.Row.Attributes.Add(“onMouseOver”, “this.style.background=’” + HighlightColor + “‘;”);

        if (e.Row.DataItemIndex % 2 == 0) { e.Row.Attributes.Add(“onMouseOut”

            , “this.style.background=’” + NormalRowColor + “‘;”); }

        else { e.Row.Attributes.Add(“onMouseOut”

            , “this.style.background=’” + AlternateRowColor + “‘;”); }

        }

    }

 

 

public static void AddMouseoverHighlightLink(GridView gv, GridViewRowEventArgs e, string formatURL, string[] URLHeaderTextArgs, string HighlightColor, string NormalRowColor, string AlternateRowColor)

{

    if (e.Row.DataItemIndex > -1)

    {

        //Create arg array of indexed columns based on URLHeaderTextArgs

        string[] Args = (string[])URLHeaderTextArgs.Clone();

        int ColumnID = -1;

        for (int i = 0; i <= URLHeaderTextArgs.GetUpperBound(0); i++)

        {

            //find column id

            ColumnID = FindGridViewColumnID(gv, URLHeaderTextArgs[i]);

            if (ColumnID == -1) { throw new Exception(“Could not add MouseOverHighlight, column ‘”

                + URLHeaderTextArgs[i] + “‘ was not found in GridView ‘” + gv.ID + “‘!”); }

            Args[i] = e.Row.Cells[ColumnID].Text;

        }

 

        e.Row.Attributes.Add(“onMouseOver”, “this.style.background=’” + HighlightColor + “‘;”);

        if (e.Row.DataItemIndex % 2 == 0)

        {

            e.Row.Attributes.Add(“onMouseOut”, “this.style.background=’” + NormalRowColor + “‘;”);

        }

        else

        {

            e.Row.Attributes.Add(“onMouseOut”, “this.style.background=’” + AlternateRowColor + “‘;”);

        }

        e.Row.Attributes.Add(“onClick”, “window.location=’” + string.Format(formatURL, Args) + “‘;”);

    }

}

 

 

<asp:GridView ID=”GridView1″ runat=”server” OnRowDataBound=”RowDataBound” ../>   

 

 That’s it!

To define page to redirect to use the AddMouseoverHighlightLink by defining the RowDataBound event in your GridView just like the RowCreated event above e.g.:

 

<asp:GridView ID=”GridView1″ runat=”server” OnRowDataBound=”OnRowDataBound” ../>

Then add an event handler in the code behind:

 

 

 

 

Here, I’ve defined a custom URL Format string that references id coluns in the GridView. You can duplicate this method or build the string using another method. When the user clicks on the row in the GridView, the page is redirected to ApprovalRequestEdit.aspx with the querystring parameters set.

- The Guru 

 

 

 

 

 

 

public void RowDataBound(object sender, GridViewRowEventArgs e)

{

    WebUtility.AddMouseoverHighlightLink((GridView)sender

    , e, “ApprovalRequestEdit.aspx?recID={0}&LoopID={1}”

    , new string[] { “Request ID”, “Loop ID” });

 

 

}

 

public void OnRowCreated(object sender, GridViewRowEventArgs e)

{

    WebUtility.AddMouseoverHighlight(e);

}

 

 

Then add an event handler in your code behind to handle the OnRowCreated event like so:

 

/// <summary>

/// Returns the index number of the column in GridView gv with HeaderText = headerText.

/// Returns -1 if column is not found

/// </summary>

/// <param name=”gv”></param>

/// <param name=”ColumnName”></param>

/// <returns></returns>

public static int FindGridViewColumnID(GridView gv, string headerText)

{

    for (int i = 0; i < gv.Columns.Count; i++)

    {

        if (gv.Columns[i].HeaderText == headerText) return i;

    }

 

    return -1;

}

 

*** END ***

Now that you’ve copied the source, define the OnRowCreated event in your GridView like so:

 

 

 

/// <summary>

/// Adds Mouseover Highlighting to rows in e’s gridview

/// </summary>

/// <param name=”e”></param>

public static void AddMouseoverHighlight(GridViewRowEventArgs e)

{

    AddMouseoverHighlight(e, “#00ffff”, “#ffffff”, “#eeeeee”);

}

Utility to automatically highlight text in a textbox when it gets the focus

Here’s a handy utility which will modify every textbox on a page and add javascript to highlight the text in the textbox when it gets the focus.

/// <summary>

/// Searches through all controls in parameter C and adds javascript to textboxes

/// to automatically select contents when each textbox gets the focus.

/// Example: SetTextBoxesToAutoselect(Page) : Sets all textboxes on current webpage

/// </summary>

/// <param name=”C”></param>

public static void SetTextBoxesToAutoselect(Control C)

{

    try

    {

        foreach (Control c in C.Controls)

        {

            if (c is TextBox)

            {

                TextBox tb = (TextBox)c;

                tb.Attributes.Add(“onfocus”, “this.select();”);

            }

            SetTextBoxesToAutoselect(c);

        }

    }

    catch (Exception)

    {

        //throw;

    }

}