Sunday, October 16, 2011

Add tooltip to each item of a DropDown list

You can do a simple DataBind() to bind the DataValue and the DataText fields To populate data into a dropdown list, I thought that binding it with the DropDown1.ToolTip = would do it, yes it does add ToolTip to each item but does not bind a different values.
like I tried to do this on a databind


    private DataTable makeTable()
    {
        DataTable t = new DataTable();
        t.Columns.Add("id");
        t.Columns.Add("display");
        t.Columns.Add("description"); // I thought this would add a tooltip to each item
        t.Rows.Add("1","item1","item1 desc");
        t.Rows.Add("2","item2","item2 desc");
        return t;
    }
    private void bingdd()
    { 
        DataTable t = makeTable();
        DropDownList1.DataValueField = "id";
        DropDownList1.DataTextField = "display";
        DropDownList1.ToolTip = "description";
        DropDownList1.DataSource = t;
        DropDownList1.DataBind();
    }

If you have table where the value, text and description are placed (I just made a datatable), and you want to display the description on mouseover of each item, then use the databound even to add attibutes each item.
The comes in the databound event that will be used to add a 'title' to each item


    private string[] descArray = new string[8];//array to store descriptions

    private void bingdd() //modified bind method
    { 
        DataTable t = makeTable();
        DropDownList1.DataValueField = "id";
        DropDownList1.DataTextField = "display";
       // DropDownList1.ToolTip = "description";
        for (int i = 0; i < t.Rows.Count; i++)
        {
            descArray[i] = t.Rows[i][2].ToString();
        }
        DropDownList1.DataSource = t;
        DropDownList1.DataBind();
    }
    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
        int i = 0;
        foreach (ListItem l in DropDownList1.Items)
        {
            l.Attributes.Add("title", descArray[i]);
            i++;
        }
    }

Then you get something like

If there is a faster or better way, tell me please

Hope this helps

No comments:

Post a Comment