天山彤佬

超级软件测试工程师

博客园 首页 新随笔 联系 订阅 管理
DataGrid是asp.net网页应用程序中常用的控件,vs2005里面改成了GridView。一般比较简单的,可以生成以下这样的数据表格。
 
有的时候,我们需要展示更复杂的内容,比如下图:
其实这也是用DataGrid生成的,由于DataGrid提供了很强大的排序、翻页等功能,我们可以利用它创建列表,就非常的轻松自如。下面说一下使用方法。
 
首先创建一个用户控件Ctrl1,比如上图那个产品展示,用户控件里定义好一个产品的样式,显示哪些内容(图片、产品名、描述)。后面数据绑定时,会反复加载这个用户控件。然后在页面上创建DataGrid控件:
<asp:DataGrid AllowPaging="True" id="ThumbsGrid" runat="server" BorderStyle="none" BorderWidth="0" CellSpacing="1" CellPadding="5" ShowHeader="False" Width="98%" OnItemDataBound="onRowBound"></asp:DataGrid>
 
在代码中,从数据库取出需要绑定的数据(比如取出的DataTable叫做contentDataTable,注意这必须是一个protected类型的全局变量)。根据contentDataTable和需要显示的列数,生成一个索引表t,将这个索引表和DataGrid进行绑定(注意,不是用contentDataTable进行绑定)。

DataTable t = new DataTable();
DataRow dr;
int picPerRow = 3;//比如显示3列数据
for(int a = 0; a != picPerRow; a++)//为索引表创建列
{
    t.Columns.Add(new DataColumn(a.ToString(), typeof(string)));
}
float frows = contentDataTable.Rows.Count / picPerRow;
int num_rows = (int)Math.Ceiling(frows);//算出一共几行
for(int b = 0; b != num_rows ; b++)
{
    dr = t.NewRow();
    for(int a = 0; a != picPerRow; a++)
    {
        int curr = (b * picPerRow) + a;
        dr[a] = curr.ToString();
    }
    t.Rows.Add(dr);
}
ThumbsGrid.DataSource = new DataView(t);
ThumbsGrid.DataBind();
 
建立一个回调函数,在数据绑定的时候调用。回调的时候注意,可能每个Row里面会有很多Cell。
protected void onRowBound(object sender, DataGridItemEventArgs e)
{
    if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        for(int a = 0; a != e.Item.Cells.Count; a++)
        {
            ReplaceCellContent(e.Item.Cells[a]);
        }
    }
}
接下来设计替换单元的代码。

private void ReplaceCellContent(TableCell i_c)
{
    string itemno = i_c.Text;
    int itn = Convert.ToInt16(itemno);//取出cell的值,实际上是原m_contentDataTable的index

    if(itn >= m_contentDataTable.Rows.Count)
    {
        i_c.Text = "";//如果index超出了原表的数据条数,往往出现在最后一行。
    }
    else
    {
        Ctrl1 ctrl = (Ctrl1) Page.LoadControl("Ctrl1.ascx");
        //根据m_contentDataTable.Rows[itn]绑定用户控件
        i_c.Controls.Clear();//要先清除原来cell里面的控件
        i_c.Controls.Add(ctrl);
    }
}
posted on 2008-03-31 00:19  陈逊  阅读(344)  评论(0编辑  收藏  举报