在DataGrid中对内容的截取

在使用DataGrid时经常遇到单元格中的内容过长而导致文本的换行,这样使本来简洁的页面看上去非常乱。下面的方法可以解决这个问题。
当单元格的内容超出指定的长度后,截去多余的字,然后在鼠标停留在某个单元格上时,就显示全部的内容。
此方法有个缺点:每个单位格都是指定长度的。
  //某个datagrid的ItemDataBound事件。
  //上半部分设置鼠标悬停时的背景色
  //下半部分才起作用
  public void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
  {
   if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
   {
    Color color = this.DataGrid1.SelectedItemStyle.ForeColor;
    string foreColor = string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
    color = this.DataGrid1.SelectedItemStyle.BackColor;
    string backColor = string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
    // 如果没有设置选中项的颜色,则不设置鼠标效果
    if(foreColor != "#000000" || backColor != "#000000")
    {
     e.Item.Attributes.Add("onmouseover", string.Format("oldItemForeColor=this.style.color;this.style.color='{0}';oldItemBackColor=this.style.backgroundColor;this.style.backgroundColor='{1}'", foreColor, backColor));
     e.Item.Attributes.Add("onmouseout", "this.style.color=oldItemForeColor;this.style.backgroundColor=oldItemBackColor;");
    }
    e.Item.Cells[1].Text = "<div style='text-overflow : ellipsis; overflow : hidden;width:80px;' title='"+e.Item.Cells[1].Text+"'><nobr>" + e.Item.Cells[1].Text + "</nobr></div>";
    e.Item.Cells[2].Text = "<div style='text-overflow : ellipsis; overflow : hidden;width:80px;' title='"+e.Item.Cells[2].Text+"'><nobr><a class=lan href='" +this.Request.ApplicationPath+@"/UpLoadFile/"+System.IO.Path.GetFileName(e.Item.Cells[7].Text)+"'>" + e.Item.Cells[2].Text + "</a></nobr></div>";
    e.Item.Cells[3].Text = "<div style='text-overflow : ellipsis; overflow : hidden;width:80px;' title='"+e.Item.Cells[3].Text+"'><nobr>" + e.Item.Cells[3].Text + "</nobr></div>";
    e.Item.Cells[4].Text = "<div style='text-overflow : ellipsis; overflow : hidden;width:80px;' title='"+e.Item.Cells[4].Text+"'><nobr>" + e.Item.Cells[4].Text + "</nobr></div>";
    e.Item.Cells[5].Text = "<div style='text-overflow : ellipsis; overflow : hidden;width:90px;' title='"+e.Item.Cells[5].Text+"'><nobr>" + e.Item.Cells[5].Text + "</nobr></div>";
    e.Item.Cells[6].Text = "<div style='text-overflow : ellipsis; overflow : hidden;width:90px;' title='"+e.Item.Cells[6].Text+"'><nobr>" + e.Item.Cells[6].Text + "</nobr></div>";
   }
  }


摘自:http://blog.csdn.net/windowsboy/archive/2004/10/18/141650.aspx
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值