asp.net gridview itemtemplate和footertemplate中的两行

时间:2017-04-24 17:08:13

标签: c# asp.net gridview

我有一个页面,我需要创建一个视图,我们可以在其中添加行,并且该视图需要看起来像这样。

enter image description here

这里第二行有一个大文本框。在填充数据并单击添加新链接时,该行应保存在DB中并且可见,并且应显示新的页脚行以填充新数据。 我通过谷歌和SO去找到ListView,DataList,但我无法想出一种方法来实现这一目标。我知道这个问题可能是重复的。但我想通过截图显示我需要的内容。

请帮助我一点,指导正确的方向。感谢。

1 个答案:

答案 0 :(得分:1)

您可以在GridView的RowCreated事件中执行此操作。但是,额外的行将放在正常的页眉和页脚行上方。在这里,您还可以根据需要向额外的行添加控件。但请记住,必须在每个PostBack上重新创建动态创建的控件,因此数据绑定不能在IsPostBack检查内。

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    //cast the sender back to a gridview
    GridView gv = sender as GridView;

    //check if the row is the header row
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //create a new row
        GridViewRow extraHeader = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
        extraHeader.BackColor = Color.Red;

        //loop all the columns and create a new cell for each
        for (int i = 0; i < gv.Columns.Count; i++)
        {
            TableCell cell = new TableCell();
            cell.Text = "ExtraHeader " + i;

            //add the cell to the new header row
            extraHeader.Cells.Add(cell);
        }

        //add the new row to the gridview
        gv.Controls[0].Controls.AddAt(0, extraHeader);
    }

    //check if the row is the footer row
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        //create a new row
        GridViewRow extraFooter = new GridViewRow(0, 0, DataControlRowType.Footer, DataControlRowState.Insert);
        extraFooter.BackColor = Color.Green;

        //add one cell with colspan 2
        TableCell cell1 = new TableCell();
        cell1.Text = "ExtraFooter 1";
        cell1.ColumnSpan = 2;
        extraFooter.Cells.Add(cell1);

        //add another one with colspanning the rest 
        TableCell cell2 = new TableCell();
        cell2.Text = "ExtraFooter 2";
        cell2.ColumnSpan = gv.Columns.Count - 2;
        extraFooter.Cells.Add(cell2);

        //add +2 to the row count. one for the extra header and 1 for the extra footer
        int insertIndex = gv.Rows.Count + 2;

        //add the new row to the gridview
        gv.Controls[0].Controls.AddAt(insertIndex, extraFooter);
    }
}