Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Datagrid Cell Tooltip

0.00/5 (No votes)
25 Sep 2009 1  
Showing Tooltip for each cell with data of a table in a Datagrid

Introduction

This article is used to display tooltip for each cell in a datagrid with datasource datatable's data in a simplified way. 

To accomplish this, We have to use ItemDataBound() event of the datagrid.  Before we begin with ItemDataBound() event, we need to set datatable for the datagrid which we use to display the data. 

Page_load() Event

    private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if( !IsPostBack)
            {
                
                dt = new DataTable();
                dt.Columns.Add("EmpNo",System.Type.GetType("System.Int32"));
                dt.Columns.Add("EmpName",System.Type.GetType("System.String"));
                dt.Columns.Add("EmpSalary",System.Type.GetType("System.Int32"));

                DataRow drow;

                drow = dt.NewRow();
                drow["EmpNo"] = 1001;
                drow["EmpName"] = "Ranjith";
                drow["EmpSalary"] = 40000;
                dt.Rows.Add(drow);

                drow = dt.NewRow();
                drow["EmpNo"] = 1003;
                drow["EmpName"] = "Surrendra";
                drow["EmpSalary"] = 30000;
                dt.Rows.Add(drow);
        

                drow = dt.NewRow();
                drow["EmpNo"] = 1002;
                drow["EmpName"] = "Thiru";
                drow["EmpSalary"] = 20000;
                dt.Rows.Add(drow);

                drow = dt.NewRow();
                drow["EmpNo"] = 1001;
                drow["EmpName"] = "Renuga";
                drow["EmpSalary"] = 10000;
                dt.Rows.Add(drow);

                DataGrid1.DataSource = dt.DefaultView;
                DataGrid1.DataBind();
            }
        }

ItemDataBound() Event

The ItemDataBound() Event gets fired when data from datatable binds with datagrid. This is where we add tooltip for each and every cell of the datagrid.

private void DataGrid1_ItemDataBound(object sender, 
        System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    if((e.Item.ItemType==ListItemType.AlternatingItem) || 
        (e.Item.ItemType==ListItemType.Item))
    {
        for(int i=0;i<e.Item.Cells.Count;i++)
        {
            e.Item.Cells[i].ToolTip= e.Item.Cells[i].Text;
        }
    }
}

Conclusion

The ItemDataBound event can be used to do anything which we want to do while datagrid data get bound. I hope this article will be useful for you all.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here