{
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.