如何将asp.net转发器控件动态绑定到数据源

时间:2014-06-03 10:40:19

标签: c# asp.net data-binding datarepeater

我在页面中有一个简单的下拉列表和转发器控件的页面。提交转发器控件绑定到有3列的datasource1。 Scenario 1

现在我的要求是如果我选择option2,它应该绑定到包含4列的datasource2。 Scenario 2

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
    <tr>
        <th align="left">Header1</th>
        <th align="left">Header3</th>
        <th align="left">Header2</th>
    </tr>
</HeaderTemplate>
<ItemTemplate>
    <tr>
        <td>
            <asp:Label ID="Header1" runat="server" /></td>
        <td>
            <asp:Label ID="Header3" runat="server" /></td>
        <td>
            <asp:Label ID="Header2" runat="server" /></td>
    </tr>
</ItemTemplate>

同一个转发器是否可以动态绑定到异构数据源?如何在运行时指定头模板和项模板?是否可以仅使用一个转发器控件和多个异构数据源来实现此方案?

5 个答案:

答案 0 :(得分:7)

以下代码感觉会对您有所帮助。

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
    <HeaderTemplate>
        <tr class="">
            <asp:Repeater ID="Header1" runat="server">
                <ItemTemplate>
                    <th align="left"><%# Container.DataItem %>
                    </th>
                </ItemTemplate>
            </asp:Repeater>
        </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr class="">
            <asp:Repeater ID="Item1" runat="server">
                <ItemTemplate>
                    <td><%# Container.DataItem %>
                    </td>
                </ItemTemplate>
            </asp:Repeater>
        </tr>
    </ItemTemplate>
</asp:Repeater>


protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) 
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            Repeater headerRepeater = e.Item.FindControl("Header1") as Repeater;
            headerRepeater.DataSource = dt.Columns;
            headerRepeater.DataBind();
        }

       if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater columnRepeater = e.Item.FindControl("Item1") as Repeater;
            var row = e.Item.DataItem as System.Data.DataRowView;
            columnRepeater.DataSource = row.Row.ItemArray;
            columnRepeater.DataBind();
        }
    }

或以其他方式使用2个不同的用户控件。第一个用户控件包含repeater1,第二个包含repeater2.Then动态地将这些中继器添加到您的页面,代码在后面

答案 1 :(得分:3)

您可以像这样使用 -

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
   {
      SqlCommand cmd = new SqlCommand("select * from Customers", con);
      cmd.CommandType = CommandType.StoredProcedure;
      SqlDataAdapter adpt = new SqlDataAdapter(cmd);
      DataTable dt = new DataTable();
      adpt.Fill(dt);
      repeaterObj.DataSource = dt;
      repeaterObj.DataBind();
      cmd.Dispose();
    }
 }

答案 2 :(得分:0)

在下拉列表中尝试设置AutoPostback = true。然后,在代码隐藏设置上有一个“selectedindexchanged”事件处理程序来读取值并相应地设置数据源,类似于:

repeater1.DataSource=<yourdatasource>
repeater1.DataBind()

如果您的数据源始终使用相同的列进行演示,那么这应该不是问题。如果您的数据源在他们返回的数据列中有所不同,那么Kashif在您的问题中的评论可能对您有所帮助。否则,您只需要填写上面的逻辑,将转发器的Datasource属性设置为您的数据源...

希望这有帮助

答案 3 :(得分:0)

        <HeaderTemplate>
            <table id="masterDataTable" class="reportTable list issues" width="100%">
                <thead>
                    <tr>
                        <asp:Literal ID="literalHeader" runat="server"></asp:Literal>
                    </tr>
                </thead>
                <tbody>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <asp:Literal ID="literals" runat="server"></asp:Literal>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </tbody> </table>
        </FooterTemplate>
    </asp:Repeater>

  // javascript Function

    <script type="text/javascript">
   $(document).ready(function () {
  $('#ddlReport').removeClass('required');
   $('.sort').click(function () {
    $('#hdnColumnName').val($(this).text());
    $('#hdnColumnOrder').val($(this).attr('class'));
    $(this).toggleClass("desc asc");
    $("#lnkSort").click();
     });
  }  );

  // Bind repeater

     DataTable dt = objReport.GetCustomRecord();
   fn = new List<string>();
   for (int i = 0; i < dt.Columns.Count; i++)
  {
    if (dt.Columns[i].ColumnName != "Maxcount" )
    {
        fn.Add(dt.Columns[i].ColumnName);
    }
}

Repeater1.DataSource = dt;
Repeater1.DataBind();



      protected void Repeater1_databinding(object sender,   RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Header)
 {
   if (e.Item.FindControl("literalHeader") != null)
   {
          StringBuilder sb = new StringBuilder();
         Literal li = e.Item.FindControl("literalHeader") as Literal;

         fieldName().ForEach(delegate(string fn)
           {
           if (hdnColumnName.Value != fn.ToString())
             {
                sb.Append("<th width=\"10%\"> <a id=\"btnCustomerName\" class=\"sort desc\" onclick=\"btnSorts_onclick()\" style=\"cursor:pointer;text-decoration: none !important;\" >"
                + fn.ToString() + "</a></th>");
             }
            else
            {
               if (hdnColumnOrder.Value == "sort asc")
                sb.Append("<th width=\"10%\"> <a id=\"btnCustomerName\" class=\"sort desc\"  onclick=\"btnSorts_onclick()\" style=\"cursor:pointer;text-decoration: none !important;\" >"
               + fn.ToString() + "</a></th>");
            else
                sb.Append("<th width=\"10%\"> <a id=\"btnCustomerName\" class=\"sort asc\" onclick=\"btnSorts_onclick()\" style=\"cursor:pointer;text-decoration: none !important;\">"
                                           + fn.ToString() + "</a></th>");
        }
    });
    li.Text = sb.ToString();

   }

 }
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
 {
 if (e.Item.FindControl("literals") != null)
 {
    DataRowView drv = (DataRowView)e.Item.DataItem;
    Literal li = e.Item.FindControl("literals") as Literal;
    StringBuilder sb = new StringBuilder();
    fieldName().ForEach(delegate(string fn)
    {
        sb.Append("<td>" + drv[fn.ToString()] + "</td>");
    });
    li.Text = sb.ToString();
 }
  }
 }

答案 4 :(得分:0)

使用bootstrap和datatables.net插件

protected void rptReport_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                Repeater headerRepeater = e.Item.FindControl("Header1") as Repeater;
                headerRepeater.DataSource = dtOrder.Columns;
                headerRepeater.DataBind();
            }

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater columnRepeater = e.Item.FindControl("Item1") as Repeater;
                var row = e.Item.DataItem as System.Data.DataRowView;
                columnRepeater.DataSource = row.Row.ItemArray;
                columnRepeater.DataBind();
            }
        }

<link href="/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
    <link href="/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />

    <div class="row">
        <div class="col-md-12">
            <asp:Panel runat="server" ID="pnlReport">
                <div class="portlet light bordered">
                    <div class="portlet-title">
                        <div class="caption font-dark">
                            <i class="icon-settings font-dark"></i>
                            <span class="caption-subject bold">Sonuçlar </span>
                        </div>
                        <div class="tools"></div>
                    </div>
                    <div class="portlet-body">
                        <asp:Repeater ID="rptReport" runat="server" OnItemDataBound="rptReport_ItemDataBound">
                            <HeaderTemplate>
                                <table class="table table-striped table-bordered table-hover" id="tblReport">
                                    <thead>
                                        <tr>
                                            <asp:Repeater ID="Header1" runat="server">
                                                <ItemTemplate>
                                                    <th><%# Container.DataItem %></th>
                                                </ItemTemplate>
                                            </asp:Repeater>
                                        </tr>
                                    </thead>
                                    <tbody>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <tr>
                                    <asp:Repeater ID="Item1" runat="server">
                                        <ItemTemplate>
                                            <td><%# Container.DataItem %></td>
                                        </ItemTemplate>
                                    </asp:Repeater>
                                </tr>
                            </ItemTemplate>
                            <FooterTemplate>
                                </tbody>
                                </table>
                            </FooterTemplate>
                        </asp:Repeater>
                    </div>
                </div>
            </asp:Panel>
        </div>
    </div>

    <script type="text/javascript" src='<%=ResolveUrl("~/jquery.min.js") %>'></script>
    <script type="text/javascript" src='<%=ResolveUrl("~/bootstrap.min.js") %>'></script>
<script src='<%=ResolveUrl("~/scripts/datatable.js") %>' type="text/javascript"></script>
    <script src='<%=ResolveUrl("~/datatables/datatables.min.js") %>' type="text/javascript"></script>
    <script src='<%=ResolveUrl("~/bootstrap/datatables.bootstrap.js") %>' type="text/javascript"></script>

<script>
        $(document).ready(function () {
            $('#tblReport').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Turkish.json",
                    "decimal": ",",
                    "thousands": ".",
                    buttons: {
                        copyTitle: 'Panoya kopyalandı',
                        copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
                        copySuccess: {
                            _: '%d satır kopyalandı',
                            1: '1 satır kopyalandı'
                        }
                    }
                },

                buttons: [
                { extend: 'print', className: 'btn dark btn-outline', text: 'Yazdır' },
                { extend: 'copy', className: 'btn red btn-outline', text: 'Kopyala' },
                { extend: 'pdf', className: 'btn green btn-outline' },
                { extend: 'excel', className: 'btn yellow btn-outline ' },
                { extend: 'csv', className: 'btn purple btn-outline ' },
                { extend: 'colvis', className: 'btn dark btn-outline', text: 'Kolonlar' }
                ],
                "order": [
                    [0, 'asc']
                ],

                "lengthMenu": [
                    [5, 10, 50, -1],
                    [5, 10, 50, "Hepsi"]
                ],
                "pageLength": 10,
                "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
            });
        });
    </script>