Mindfire Solutions
Home  |  Faq  |  Site map  |  Contact
Email sales@ or Call 1-248-686-1424
Share | Share on Facebook Share on Twitter Share On Linkedin
Add tooltip to Datagrid item cell when text length exceeds the item cell length
Author: Jnana Swain
If tooltip property of datagrid cell is used (e.Item.Cells[0].ToolTip), tooltip will be shown but large text may not be well truncated.
i.e the characters may not be fully padded up to the last pixel of cell, it may be truncated at the middle of the cell or any where in the cell.
 
Item Bound
 DataRowView rowview = (DataRowView)e.Item.DataItem;
 if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
 {
    e.Item.Cells[0].Width  = 100;
    string res = Convert.ToString(rowview["Result"]);
    if( res.Length > 10 ) // 10 is adjusted for 100px width it can be changed
    {
      e.Item.Cells[0].ToolTip = Convert.ToString(rowview["Result"]);
      e.Item.Cells[0].Text = res.Substring(0,10);
    }
     else
    {
      e.Item.Cells[0].Text = res;
    }
}

Because characters A ,a ,#,@ do not occupy same no of pixel or users browser may have different pixel format.
Solutions :-
 
Aspx Code:-

 <style type="text/css">
    .tds { OVERFLOW: hidden; TEXT-OVERFLOW: ellipsis }
 </style>
 <script language="JavaScript">
 function Tooltip() // When Mouse over to Item       
 {
       // Put the text in divForTextWidth for pixel occupy by the text.
        var noBrWidth = event.srcElement;
        divForTextWidth.innerText = noBrWidth.innerText;
        if(divForTextWidth.clientWidth > noBrWidth.clientWidth )
        {
          noBrWidth.title =noBrWidth.innerText
        }
 }
 </script>
 
 <asp:DataGrid ID="dgToolTip" Runat="server" AutoGenerateColumns="False" ItemStyle-Width="100px">
 <columns>
 <asp:boundcolumn DataField="Result" HeaderText="Result"></asp:boundcolumn>
 </columns>
 </asp:DataGrid
>
 
 <div id="divForTextWidth" style=' PADDING-RIGHT:0px;
 PADDING-LEFT:0px;
 Z-INDEX:102;
 LEFT:5px;
 VISIBILITY:hidden;
 PADDING-BOTTOM:0px;
 COLOR:#ff0000;
 PADDING-TOP:0px;
 POSITION:absolute;
 TOP:5px;
 borderWidth:0px;
 z-:100'>
 </div>
 
CS Code:-
Page Load

string connectionString = "server=servername;user id = userid;password = password;database=jrs";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select result from result",connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
dgToolTip.DataSource = ds;
dgToolTip.DataBind();
 
Item Bound
DataRowView rowview = (DataRowView)e.Item.DataItem;
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
 e.Item.Cells[0].Text = "<nobr class=tds  style="+ "width:100px;" +  "   onmouseover=Tooltip();" +">" + Convert.ToString(rowview["Result"]) + "</nobr>";
    e.Item.Cells[0].Attributes.Add("onmouseover", "this.style.cursor='default'");
}

Related Tags:
ASP.NET

top