在DataGrid中對內容的截取[Come From WindowsBoy]

來源:互聯網
上載者:User
在使用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>";
   }
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.