使用autogeneratedcolumns选项'true'自定义gridview并从pivot数据表中绑定数据?

时间:2013-03-26 15:05:04

标签: c# asp.net

我已在此处提出此问题:Table with dynamic number of columns to show

但是我对这个问题还有一些问题。

1.我有一个数据表,其中包含保险名称,种类,保险费....“每行

在我的前端,我需要表现出:

Insurance Name     HealthNet       Harvard         UniCare

Plan Type            HMO            PPO              HMO  

Premium              100            150             200 

为此,我使用以下方法来旋转数据表并将其分配给gridview)

private DataTable PivotTable(DataTable origTable){

        DataTable newTable = new DataTable();
        DataRow dr = null;
        //Add Columns to new Table
        for (int i = 0; i <= origTable.Rows.Count; i++)
        {
            newTable.Columns.Add(new DataColumn(origTable.Columns[i].ColumnName, typeof(String)));
        }

        //Execute the Pivot Method
        for (int cols = 0; cols < origTable.Columns.Count; cols++)
        {
            dr = newTable.NewRow();
            for (int rows = 0; rows < origTable.Rows.Count; rows++)
            {
                if (rows < origTable.Columns.Count)
                {
                    dr[0] = origTable.Columns[cols].ColumnName; // Add the Column Name in the first Column
                    dr[rows + 1] = origTable.Rows[rows][cols];
                }
            }
            newTable.Rows.Add(dr); //add the DataRow to the new Table rows collection
        }
        return newTable;
}

数据绑定如下:

DataTable tempTable = PivotTable(actualDataTable);
myGridView.DataSource = tempTable;
myGridView.DataBind();

现在我的出局看起来像:

Insurance Name     HealthNet       Harvard         UniCare

Plan Type            HMO            PPO              HMO  

Premium              100            150             200 

但现在我的网格视图显示了数据源中的所有值。我想自定义我的网格视图外观这样我就可以将图像插入到每个保险名称旁边的表格行中,并隐藏一些行。

注意:我不仅限于gridview。我对任何控制都很好,但数据应该是动态的而不是硬编码。

由于

编辑:

我可以根据列数循环,而不是跟随每个保险名称旁边的显示图像。

protected void myGridview_RowDataBound(Object sender, GridViewRowEventArgs e)
    {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[1].Text = "<img src=../images/" + e.Row.Cells[1].Text + ".png />";
                e.Row.Cells[2].Text = "<img src=../images/" + e.Row.Cells[2].Text + ".png />";

            }

    }

1 个答案:

答案 0 :(得分:0)

您可以使用GridView的RowDataBound事件。

在RowDataBound事件中,您可以操纵每个单元格的数据。例如,将图像插入单元格。

但是,您无法隐藏整行。如果您不想显示行,则需要在数据透视表方法中实现该逻辑。

相关问题