读出数据库数据,控制显示长度!

public void BindGrid()
  {
   OleDbConnection myConnection = cn;
   DataSet ds  = new DataSet();
   OleDbDataAdapter adapter  = new OleDbDataAdapter("Select Title,CreateDate from article", myConnection);
   adapter.Fill(ds, "Document");
//这里开始
   for(int i=0;i<ds.Tables[0].Rows.Count;i++)
   {
    if(ds.Tables[0].Rows[i]["Title"].ToString().Length>6)
     ds.Tables[0].Rows[i]["Title"]=CutString(ds.Tables[0].Rows[i]["Title"].ToString(),6);
   }
   MyDataGrid.DataSource = ds.Tables["Document"].DefaultView;
            MyDataGrid.DataBind();
   ShowStats();
  }

#region 字符串截取函数
  public static string CutString(string inputString,int len)
  {


   ASCIIEncoding ascii =  new ASCIIEncoding();
   int tempLen=0;
   string tempString="";
   byte[] s = ascii.GetBytes(inputString);
   for(int i=0;i<s.Length;i++)
   {
    if((int)s[i]==63)
    {
     tempLen+=2;
    }
    else
    {
     tempLen+=1;
    }
               
    try
    {
     tempString+=inputString.Substring(i,1);
    }
    catch
    {
     break;
    }

    if(tempLen>len)
     break;
   }
   //如果截过则加上半个省略号
   byte[] mybyte=System.Text.Encoding.Default.GetBytes(inputString);
   if(mybyte.Length>len)
    tempString+="…";


   return tempString;
  }
  #endregion

我的方法是,达到一定长度后,取子串显示,鼠标移动到上面时,显示全部内容。
private void dgAll_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
{
e.Item.Cells[0].Attributes.Add("onmousemove", "javascript:moveinfo();");
e.Item.Cells[0].Attributes.Add("onmouseover", "javascript:showinfo(this,'" + e.Item.Cells[0].Text + "','" + e.Item.Cells[2].Text + "','" + e.Item.Cells[3].Text +"');");
e.Item.Cells[0].Attributes.Add("onmouseout", "javascript:clearinfo();");
if(e.Item.Cells[0].Text.Length > 4)
{
e.Item.Cells[0].Text = e.Item.Cells[0].Text.Substring(0,4) + "...";
}
if(e.Item.Cells[2].Text.Length > 4)
{
e.Item.Cells[2].Text = e.Item.Cells[2].Text.Substring(0,4) + "...";
}
}
}

我感觉你的代码复杂了点,我给个我的方法

public string StrCut(string str,int length)
{
string str=str;
if(str.Length<length)
{
return str;
}
else
{
return str.Substring(0,16)+"";
}
} # re: [原创]读出数据库数据,控制显示长度! 2004-08-17 08:52 format
上面有点小错误
return str.Substring(0,16)+"";
16应该为length.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值