需求千奇百怪,有的要求表格裡的內容自動換行,有的不要求,其實設置DataGrid的CSS樣式單屬性即可實現大部分的需求,但對於不換行的實現,單靠樣式單還不能完全滿足要求,下面就是一種解決的方法:
<%@ Page Language="<a href="http://dev.21tx.com/dotnet/csharp/" target="_blank">C#</a>" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
<Html>
<script runat="server">
int start_index;
ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = start_index; i < start_index + ItemsGrid.PageSize; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = @"我是中文文字,I am English Words,我不想換行,
I don't wanna have new lines,歡迎訪問
<a href='http://dotnet.aspx.cc/'>http://dotnet.ASPx.cc/</a>,
有好料啊:)";
dr[2] = 1.23 * (i+1);
dt.Rows.Add(dr);
}
DataView dv = new DataVIEw(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
//對於沒有數字的內容,下面這行完全滿足要求,但加了數字就不行,必須調用OnItemDataBound
ItemsGrid.Attributes.Add("style","word-break:keep-all;Word-wrap:normal");
//下面這行是自動換行
//ItemsGrid.Attributes.Add("style","word-break:break-all;word-wrap:break-Word");
if (!IsPostBack)
{
BindGrid();
}
}
void BindGrid()
{
ItemsGrid.DataSource=CreateDataSource();
ItemsGrid.DataBind();
}
void Item_DataBound(Object sender, DataGridItemEventArgs e)
{
if( e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
e.Item.Cells[1].Text = "<nobr>" + e.Item.Cells[1].Text + "</nobr>";
}
</script>
<body>
<form runat="server">
<ASP:DataGrid id="ItemsGrid" runat="server" BorderColor="black"
OnItemDataBound="Item_DataBound" AutoGenerateColumns="false">
<AlternatingItemStyle BackColor="#DEDEDE"></AlternatingItemStyle>
<HeaderStyle BackColor="#EEEEFF" HorizontalAlign="Center"></HeaderStyle>
<Columns>
<ASP:BoundColumn HeaderText="序號" DataFIEld="IntegerValue"/>
<ASP:BoundColumn HeaderText="文字" DataFIEld="StringValue"/>
<ASP:BoundColumn HeaderText="價格" DataFIEld="CurrencyValue" DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="right"></ItemStyle>
</ASP:BoundColumn>
</Columns>
</ASP:DataGrid>
</form>
</body>
</Html>