用DataGrid绑定复杂样式的控件

DataGrid是asp.net网页应用程序中常用的控件,vs2005里面改成了GridView。一般比较简单的,可以生成以下这样的数据表格。
331514867.jpg
 
有的时候,我们需要展示更复杂的内容,比如下图:
328668882.jpg
其实这也是用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);
    }
}

转载于:https://www.cnblogs.com/powerson/archive/2008/03/31/2091009.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值