Подтвердить что ты не робот

Вставка таблицы в одну ячейку внутри ретранслятора

Я пытаюсь построить структуру таблицы, используя asp.net Repeater, как показано ниже:

        column 1      |      Column 2

Row1      cell1               cell2
---------------------------------------
       TABLE 1                 TABLE 2
    ----------------------------------
        col1|Col2|Col3_     same  column and rows are here as well   
Row2    row1____|____|____  
        row2___ |____|_____  
        row3____|____|_____

Но я застрял в добавлении Таблица 1 и Таблица 2 для Строка 2. Я не уверен, как добавить таблицу в одну ячейку внутри Repeater, и данные должны привязываться к DataTable.

И ниже мой код для Repeater:

<asp:Repeater ID="Repeaterp" runat="server">
    <HeaderTemplate>
        <table>
            <tr><th>usedcount</th><th>notUsedCount</th></tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td><asp:TextBox runat="server" ID="txtAvai" Text='<%#Eval("Count") %>' ReadOnly="true"></asp:TextBox></td>
            <td><asp:TextBox runat="server" ID="txtConv" Text='' ReadOnly="true"></asp:TextBox></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater

Может кто-нибудь предложить любую идею по этому поводу, которая была бы мне очень благодарна?

4b9b3361

Ответ 1

Внутри регулятора Repeater можно вставить различные элементы управления представлением данных asp.net(например, asp:Repeater, asp:DataList, asp:GridView или asp:Table и т.д.). Я добавил быстрый пример для создания вложенной структуры с несколькими элементами Repeater:

.Aspx Код:

<asp:Repeater ID="RepeaterTable" OnItemDataBound="RepeaterTable_ItemDataBound" runat="server">
    <HeaderTemplate>
        <table>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <asp:Panel ID="PanelTextBoxes" runat="server">
            <tr>
                <td>
                    <asp:TextBox ID="txtAvai" Text='<%# Eval("Count") %>' runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:TextBox ID="txtConv" Text='' runat="server"></asp:TextBox>
                </td>
            </tr>
        </asp:Panel>
        <asp:Panel ID="PanelTables" runat="server">
            <tr>
                <td>
                    <asp:Repeater ID="RepeaterTable1" OnItemDataBound="RepeaterTable1_ItemDataBound" runat="server">
                        <HeaderTemplate>
                            <table>
                                <tr>
                                    <th>T1 Col 1</th>
                                    <th>T1 Col 2</th>
                                </tr>
                        </HeaderTemplate>
                        <ItemTemplate>
                                <tr>
                                    <td>
                                        <asp:Label ID="lblCol1" runat="server" Text='<%# Eval("Col1") %>'></asp:Label>
                                    </td>
                                    <td>
                                        <asp:Label ID="lblCol2" runat="server" Text='<%# Eval("Col2") %>'></asp:Label>
                                    </td>
                                </tr>
                        </ItemTemplate>
                        <FooterTemplate>
                            </table>
                        </FooterTemplate>
                    </asp:Repeater>
                </td>
                <td>
                    <asp:Repeater ID="RepeaterTable2" OnItemDataBound="RepeaterTable2_ItemDataBound" runat="server">
                        <HeaderTemplate>
                            <table>
                                <tr>
                                    <th>T2 Col 1</th>
                                    <th>T2 Col 2</th>
                                </tr>
                        </HeaderTemplate>
                        <ItemTemplate>
                                <tr>
                                    <td>
                                        <asp:Label ID="lblCol1" runat="server" Text='<%# Eval("Col1") %>'></asp:Label>
                                    </td>
                                    <td>
                                        <asp:Label ID="lblCol2" runat="server" Text='<%# Eval("Col2") %>'></asp:Label>
                                    </td>
                                </tr>
                        </ItemTemplate>
                        <FooterTemplate>
                            </table>
                        </FooterTemplate>
                    </asp:Repeater>
                </td>
            </tr>
        </asp:Panel>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

.Aspx.cs Код:

DataTable TempDT = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        getData();
    }
}

// create DataTable 3 x 2
public void getData()
{
    TempDT = new DataTable();
    TempDT.Columns.Add("Col1");
    TempDT.Columns.Add("Col2");
    TempDT.Columns.Add("Count");
    TempDT.Rows.Add("Temp", "Temp", 100);
    TempDT.Rows.Add("Temp", "Temp", 100);
    TempDT.Rows.Add("Temp", "Temp", 100);

    // store DataTable into ViewState from lost on PostBack
    ViewState["DT"] = TempDT;

    RepeaterTable.DataSource = TempDT;
    RepeaterTable.DataBind();
}

// Calls parent Repeater on Binding Data
protected void RepeaterTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // check Repeater item type is not in edit mode
    if (e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataTable dt = new DataTable();

        // get and set DataTable from ViewState
        dt = ViewState["DT"] as DataTable;

        Repeater RepeaterTable1 = e.Item.FindControl("RepeaterTable1") as Repeater;
        Repeater RepeaterTable2 = e.Item.FindControl("RepeaterTable2") as Repeater;

        RepeaterTable1.DataSource = dt;
        RepeaterTable1.DataBind(); // calls RepeaterTable1_ItemDataBound event

        RepeaterTable2.DataSource = dt;
        RepeaterTable2.DataBind(); // // calls RepeaterTable2_ItemDataBound event

        Panel PanelTextBoxes = e.Item.FindControl("PanelTextBoxes") as Panel;
        Panel PanelTables = e.Item.FindControl("PanelTables") as Panel;

        // show only first structure
        if (e.Item.ItemIndex != 0)
        {
            PanelTextBoxes.Visible = false;
            PanelTables.Visible = false;
        }        
    }
}

// Calls child Repeater on Binding Data
protected void RepeaterTable1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // check Repeater item type is not in edit mode
    if (e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        //.. here is code when child repeater is binding
    }
}

// Calls child Repeater on Binding Data
protected void RepeaterTable2_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // check Repeater item type is not in edit mode
    if (e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        //.. here is code when child repeater is binding
    }
}

Демо-изображение:

введите описание изображения здесь

Обновление:

Если вы не хотите повторять всю структуру, просто добавьте ниже код в событие RepeaterTable_ItemDataBound:

Panel PanelTextBoxes = e.Item.FindControl("PanelTextBoxes") as Panel;
Panel PanelTables = e.Item.FindControl("PanelTables") as Panel;

if (e.Item.ItemIndex != 0)
{
    PanelTextBoxes.Visible = false;
    PanelTables.Visible = false;
}

Не повторяется демонстрация всей структуры изображения:

введите описание изображения здесь

Ответ 2

Зачем беспокоиться о добавлении двух таблиц в второй элемент повторителя? Это не требовало, чтобы Repeater == Table

Вместо этого в репитере <headertemplate> поместите первую строку таблицы Master, а вторую строку со всеми 2 таблицами, которые вы хотите внутри. Затем сохраните повторитель <ItemTemplate> для остальных строк (из третьей строки вниз)

Вы можете получить доступ к двум таблицам через свой код позади или установить значения со свойствами или Eval

Вот как выглядит ваш .aspx: (Я добавил XmlDataSource1 для ретранслятора только для того, чтобы сделать привязку, я также использовал свойство <%= this.ContentString %>, которое я объявлю и установлю в коде после этого)

   <asp:Repeater ID="Repeaterp" runat="server" DataSourceID="XmlDataSource1">
        <HeaderTemplate>
            <table>
                <%--------Your Master Table--------%>
                <tr>
                    <th>usedcount
                    </th>
                    <th>notUsedCount
                    </th>
                </tr>
                <tr>
                    <td>Row1 Cell1</td>
                    <td>Row1 Cell2</td>
                </tr>
                <tr>
                    <td>
                        <%----------------First Inner Table------------------%>
                        <asp:Table ID="Table1" runat="server">
                            <asp:TableHeaderRow>
                                <asp:TableHeaderCell>
                        Header
                                </asp:TableHeaderCell>
                                <asp:TableHeaderCell>
                        Header
                                </asp:TableHeaderCell>
                            </asp:TableHeaderRow>
                            <asp:TableRow>
                                <asp:TableCell>
                        <%---Add your conents as properties----%>
                                 <%= this.ContentString %>

                                </asp:TableCell>
                                <asp:TableCell>

                                </asp:TableCell>
                            </asp:TableRow>

                            <asp:TableRow>
                                <asp:TableCell>                         
                                    content
                                </asp:TableCell>
                                <asp:TableCell>
                                    content
                                </asp:TableCell>
                            </asp:TableRow>
                            <asp:TableRow>
                                <asp:TableCell>                         
                                    content
                                </asp:TableCell>
                                <asp:TableCell>
                                    content
                                </asp:TableCell>
                            </asp:TableRow>
                        </asp:Table>

                    </td>
                    <td>

                        <%----------------Second Inner Table------------------%>
                        <asp:Table ID="Table2" runat="server">
                            <asp:TableHeaderRow>
                                <asp:TableHeaderCell>
                        Header
                                </asp:TableHeaderCell>
                                <asp:TableHeaderCell>
                        Header
                                </asp:TableHeaderCell>
                            </asp:TableHeaderRow>
                            <asp:TableRow>
                                <asp:TableCell>
                        <%---Add your conents as properties----%>
                                 <%= this.ContentString %>

                                </asp:TableCell>
                                <asp:TableCell>

                                </asp:TableCell>
                            </asp:TableRow>

                            <asp:TableRow>
                                <asp:TableCell>                         
                                    content
                                </asp:TableCell>
                                <asp:TableCell>
                                    content
                                </asp:TableCell>
                            </asp:TableRow>
                            <asp:TableRow>
                                <asp:TableCell>                         
                                    content
                                </asp:TableCell>
                                <asp:TableCell>
                                    content
                                </asp:TableCell>
                            </asp:TableRow>
                        </asp:Table>
                    </td>
                </tr>
                <%-- Closing the second row of master table --%>
                <%-- Everything is completed in the repeater header! --%>
        </HeaderTemplate>

        <ItemTemplate>
            <tr>
                <td><%--continue master table as usual--%> </td>
                <td></td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </Table>
        </FooterTemplate>
    </asp:Repeater>

Здесь код, обратите внимание на свойство ContentString. и как получить доступ к таблицам в строке 2 после привязки ретранслятора:

                public partial class _Default : Page
                {
                    private string strContent;

                    // notice the property that the tables can read as in the aspx code above
                    public String ContentString
                    {
                        get { return strContent; }
                    }

                    protected void Page_Load(object sender, EventArgs e)
                    {
                        strContent = "Your Content";

                        Repeaterp.DataBind();
                        // here how to access the two tables
                        Table Table1 = (Table)Repeaterp.Controls[0].FindControl("Table1");
                        Table Table2 = (Table)Repeaterp.Controls[0].FindControl("Table2");
                    }
                }

Ответ 3

Если вы действительно хотите иметь таблицу во второй строке ретранслятора, вы можете сделать следующее.

Добавьте два PlaceHolder в ItemTemplate. Один для второй строки с таблицами и один для остальных строк. Установите их базы видимости на ItemIndex. Обратите внимание, что GridViews были использованы, поскольку они становятся элементами таблицы в HTML.

<ItemTemplate>

    <asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible='<%# Container.ItemIndex != 1 %>'>
        <tr>
            <td>
                <asp:TextBox runat="server" ID="txtAvai" Text='<%#Eval("Count") %>' ReadOnly="true">
                </asp:TextBox>
            </td>
            <td>
                <asp:TextBox runat="server" ID="txtConv" Text='' ReadOnly="true">
                </asp:TextBox>
            </td>
        </tr>
    </asp:PlaceHolder>

    <asp:PlaceHolder ID="PlaceHolder2" runat="server" Visible='<%# Container.ItemIndex == 1 %>'>
        <tr>
            <td>
                <asp:GridView ID="GridView1" runat="server"></asp:GridView>
            </td>
            <td>
                <asp:GridView ID="GridView2" runat="server"></asp:GridView>
            </td>
        </tr>
    </asp:PlaceHolder>

</ItemTemplate>

Если вы хотите, чтобы строка 3 снова была двумя текстовыми полями, а затем строка 4 таблицы и т.д., используйте свойство Container.ItemIndex % 2 == 0 и Container.ItemIndex % 2 == 1 в свойстве видимости PlaceHolder, потому что вышеприведенное демо занимает всего 2 строки в Repeater.

Затем добавьте событие OnItemDataBound в ретранслятор.

<asp:Repeater ID="Repeaterp" runat="server" OnItemDataBound="Repeaterp_ItemDataBound">

И затем в коде позади видеть, является ли связанный элемент второй строкой, найдите GridViews и привяжите данные к ним. Я создал фиктивный DataTable для этой демонстрации, но вы можете связать любой источник с ними в методе Repeaterp_ItemDataBound

protected void Repeaterp_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    //check if it is the second row
    if (e.Item.ItemIndex == 1)
    {
        //find the gridviews in the repeater item using findcontrol
        GridView gv1 = e.Item.FindControl("GridView1") as GridView;
        GridView gv2 = e.Item.FindControl("GridView2") as GridView;

        //create a dummy datatable for this demo
        DataTable table = new DataTable();
        table.Columns.Add("Col1", typeof(int));
        table.Columns.Add("Col2", typeof(string));
        table.Columns.Add("Col3", typeof(string));

        //add some rows to the table
        table.Rows.Add(0, "Row 1", "AAA");
        table.Rows.Add(1, "Row 2", "BBB");
        table.Rows.Add(2, "Row 3", "CCC");

        //bind the data to the gridviews in the second row
        gv1.DataSource = table;
        gv2.DataSource = table;

        gv1.DataBind();
        gv2.DataBind();
    }
}

Ответ 4

Я дам вам логику, как сделать, а не кодирование, поскольку я занят в эти дни.

1) добавьте событие ItemDataBound в родительский ретранслятор (предположим id = "parentrepeater".

2) добавьте дочерний ретранслятор в ваш ретранслятор itemtemplate в файле aspx (предположим id = "childrepeater".

3) в родительском ретрансляторе ItemDataBound, найдите дочерний ретранслятор и привяжите источник данных.

protected void parent_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // check Repeater item type is not in edit mode
    if (e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Repeater childRepeater = e.Item.FindControl("childrepeater") as Repeater;
        childRepeater.DataSource = "Get Your Datasource here";
        childRepeater.DataBind();  
    }
}

Используя этот метод, вы можете получить неограниченный многоуровневый вложенный ретранслятор.