Search code examples
c#asp.nettooltip

How to add tooltips to button define behind with C#


I defined buttons in a for loop in behind with C#

protected void GenTable()
{
    for (int r = 0; r < 100; r++)
    {
        var buttonField = new ButtonField
        {
            ButtonType = ButtonType.Button,
            Text = "Model",
            CommandName = "Display",
        };
        Model.Columns.Add(buttonField);
        break;
    }      
}​

How can I add tooltips to these buttons? I trid to add tooltip or title into the for loop but doesn't work. Can anyone help me fix it? Thanks


Solution

  • There is no option to do what you want with a System.Web.UI.WebControls.ButtonField.

    However, there is a possible workaround. You can set its Text property as it was an HTML, e.g

    <asp:ButtonField Text="<span title='My beautiful button'>Model</span>" /> 
    

    Update

    Since you're setting the Text through C#, it seems that they unescape the <, > characters.

    So, another workaround is by using the RowDataBound event. E.g: Given a GridView like this:

    <asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" runat="server">
    

    With the first column as follows:

    <asp:ButtonField Text="Model" />
    

    You can use the event ItemDataBound event below:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            (((System.Web.UI.WebControls.WebControl)e.Row.Cells[0].Controls[0])).ToolTip = "My beautiful button";
        }
    }
    

    Note: change the Cells[0] to the index of the column you want, so if you have created 100 columns, and want to show 100 tooltips (like your code does), you must loop there and change to Cells[i].