2008年11月7日 星期五

GrideView 實現跨欄作法

一個透過 GridView 達到跨欄效果的方法:
書名作者備註
Name1Author1跨欄資料
Name2Author2
Name3Author3
Name4Author4
Name5Author5


在 aspx 頁面,放置一個 GridView


<asp:GridView ID="gv" BorderColor="black" runat="server" AutoGenerateColumns="False" OnRowDataBound="gv_RowDataBound">
<Columns>
<asp:BoundField DataField="BookName" HeaderText="書名" />
<asp:BoundField DataField="Author" HeaderText="作者" />
<asp:BoundField HeaderText="備註" />
</Columns>
</asp:GridView>


定義自定的類別,以供 GridView 當資料來源


public class CBook
{
private string _BookName = string.Empty;
private string _Author = string.Empty;

public string BookName
{
get { return _BookName; }
set { _BookName = value; }
}

public string Author
{
get { return _Author; }
set { _Author = value; }
}
}


.cs 的程式


ArrayList alBook = new ArrayList();

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitBookData();
gv.DataSource = alBook;
gv.DataBind();
}
}

private void InitBookData()
{
CBook cb = null;

for (int i = 0; i < 5; i++)
{
cb = new CBook();
cb.BookName = string.Format("Name{0}", i + 1);
cb.Author = string.Format("Author{0}", i + 1);
alBook.Add(cb);
}
}

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCellCollection tcc = e.Row.Cells;
if (e.Row.RowIndex == 0)
{
tcc[2].RowSpan = 5;
tcc[2].Text = "跨欄資料";
}
else
{
tcc.Clear();
tcc.Add(new TableCell());
tcc[0].Text = Convert.ToString(DataBinder.Eval(e.Row.DataItem,"BookName"));
tcc.Add(new TableCell());
tcc[1].Text = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Author"));
}


}
}

沒有留言:

張貼留言