Como vincular dinamicamente asp.net repetidor de controlo de origem de dados
-
21-12-2019 - |
Pergunta
Eu tenho uma página com um simples suspensa e repetidor de controle na página.envio de controlo de repetidor está vinculado para datasource1 que tem 3 colunas.
Agora, a minha exigência é que se eu selecionar option2 , ele deve ligar para datasource2 que contém 4 colunas.
<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>
É possível que o mesmo repetidor para vincular dinamicamente a fontes de dados heterogêneas?Como posso especificar o modelo de cabeçalho e item de modelos em tempo de execução?Pode este cenário ser implementado com apenas um repetidor de controle e de múltiplas fontes de dados heterogêneas?
Solução
Sente código abaixo vai ajudar você .
<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();
}
}
ou de outra forma, usando 2 diferentes de controle do Usuário.Primeiro controlo de utilizador contêm repeater1, segundo contêm repeater2.Em seguida, dinâmico adicionar esses repetidores para a sua página, no código de trás
Outras dicas
Você pode simplesmente usar como esta -
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();
}
}
Tente configurações AutoPostback=true no dropdownlist.Então, ter um "selectedindexchanged" manipulador de eventos no code-behind de instalação para ler o valor e definir a origem de dados de acordo, algo semelhante a:
repeater1.DataSource=<yourdatasource>
repeater1.DataBind()
Se a sua origem é sempre usar a mesma colunas para a sua apresentação, então este não deve ser um problema.Se suas fontes de dados irá variar nas colunas de dados que retornam, então Kashif o comentário na sua pergunta pode ajudar alguns.Caso contrário, você só precisa preencher a lógica acima para definir a propriedade Datasource do seu repetidor para qualquer que seja a sua origem é...
Espero que isso ajude
<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();
}
}
}
Com bootstrap e datatables.net plugins
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>