Data binding in asp.net : listview - c#

I'm new to web development using .net and am having issues in binding data from business logic to a table. I'm basically trying to populate a table dynamically.
Table in a list view i want to populate
<asp:ListView ID="processList" runat="server"
DataKeyNames="procName" GroupItemCount="1"
ItemType="SerMon.RemoteProcess" SelectMethod="fetchFromQueue">
<EmptyDataTemplate>
<table >
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<EmptyItemTemplate>
<td/>
</EmptyItemTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server"></td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td runat="server">
<table id="myTable" class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Process</th>
<th>Status</th>
<th>Machine</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<asp:Label runat="server" ID="lblId"><%#: Item.ProcName%></asp:Label></td>
<td>
<asp:Label runat="server" ID="Label1"><%#: Item.Procstatus%></asp:Label></td>
<td>
<asp:Label runat="server" ID="Label2"><%#: Item.mcName%></asp:Label></td>
</tr>
<tr>
</tbody>
</table>
</p>
</td>
</ItemTemplate>
</asp:ListView>
Method which is called to populate table
public List<RemoteProcess> fetchFromQueue()
{
List<RemoteProcess> pl = new List<RemoteProcess>();
foreach (CloudQueueMessage message in queue.GetMessages(5, TimeSpan.FromMinutes(1)))
{
Debug.Write(message.AsString);
RemoteProcess m = JsonConvert.DeserializeObject<RemoteProcess>(message.AsString);
pl.Add(m);
//queue.DeleteMessage(message);
}
return pl;
}
The table is generated but theres no data. Also for some odd reason, five tables are generated( This is always equal to the number specified in the getMessage function)

I am not sure if GroupTemplate is required for you in the ListView. The reason you were getting multiple table was that you have defined table header and row both in the item template. The ItemTemplate should have only structure of the item display. The LayoutTemplate should have the structure of the over all layout of how data should look like.
I have changed the ListView as following it make it look like a proper table.
<asp:ListView ID="processList" runat="server"
DataKeyNames="procName"
ItemType="WebApplication1.Models.RemoteProcess" SelectMethod="fetchFromQueue">
<EmptyDataTemplate>
<table>
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<EmptyItemTemplate>
<td />
</EmptyItemTemplate>
<LayoutTemplate>
<table runat="server" id="table1">
<thead>
<tr runat="server">
<th>#</th>
<th>Process</th>
<th>Status</th>
<th>Machine</th>
</tr>
<tr id="itemPlaceholder" runat="server"></tr>
</thead>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>1</td>
<td>
<asp:Label runat="server" ID="lblId"><%#: Item.procName%></asp:Label></td>
<td>
<asp:Label runat="server" ID="Label1"><%#: Item.Procstatus%></asp:Label></td>
<td>
<asp:Label runat="server" ID="Label2"><%#: Item.mcName%></asp:Label></td>
</tr>
</ItemTemplate>
</asp:ListView>
Please note here that I have removed the GroupTemplate and setting related to it as I wasn't sure how to group the data.
This should help resolving your issue.

Related

Databinding multiple records to a single vertical-column table in asp.net gridview

I fetch data by using a selectmethod and it works fine , the problem is that I don't want a new table for each record inserted. I'd like a new column to be added to the existing table. Something like the picture below
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="FormView1" runat="server" ShowHeader="False" ItemType="MieleRepresentative.SteamBoiler" SelectMethod="GetSteamBoilerModels" RenderOuterTable="false" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table class="table-striped table-bordered">
<tr style="background-color: thistle!important;">
<td style="font-weight: bold;">Model</td>
<td><%# Eval("Model")%></td>
</tr>
<tr>
<td style="font-weight: bold">WorkingPressureLimit</td>
<td><%# Eval("WorkingPressureLimit")%></td>
</tr>
<tr>
<td style="font-weight: bold">TestPressureLimit</td>
<td><%# Eval("TestPressureLimit")%></td>
</tr>
<tr>
<td style="font-weight: bold">Electrical</td>
<td><%# Eval("Electrical")%></td>
</tr>
<tr>
<td style="font-weight: bold">Diameter</td>
<td><%# Eval("Diameter")%></td>
</tr>
<tr>
<td style="font-weight: bold">Height</td>
<td><%# Eval("Height")%></td>
</tr>
<tr>
<td style="font-weight: bold">Weight</td>
<td><%# Eval("Weight")%></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public IQueryable<SteamBoiler> GetSteamBoilerModels([QueryString("productID")] Guid productId)
{
var _mieleDbEntities = new MieleDBEntities();
return _mieleDbEntities.SteamBoilers.Where(boiler => boiler.FKProduct == productId);
}
If you want a table with an undefined number of columns (one for each record selected), probabily GridView is not your best bet.
In my opinion you should build dynamically your table in .aspx page in this way:
<% var steamBoilersList = GetSteamBoilerModels(...params...); %>
<table>
<!-- first row -->
<tr>
<% foreach (var singleSteamBoiler in steamBoilersList) { %>
<td>
<%= singleSteamBoiler.FIELD1 %>
</td>
</tr>
<!-- second row and so on -->
<tr>
<% foreach (var singleSteamBoiler in steamBoilersList) { %>
<td>
<%= singleSteamBoiler.FIELD2 %>
</td>
</tr>
</table>

How to bind a column header in listview control?

I want to bind a listview control with a datatable , whose column names are not fixed. And i want to display these column names in the page ?
How to achieve this ?
I dont know what exactly you want to do but this is the example of listview that you can set header name whatever you want.
<asp:ListView ID="ListView1" GroupPlaceholderID="group" GroupItemCount="1" ItemPlaceholderID="item" runat="server">
<LayoutTemplate>
<table>
<asp:PlaceHolder runat="server" ID="group"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<asp:PlaceHolder runat="server" ID="item"></asp:PlaceHolder>
</tr>
</GroupTemplate>
<ItemTemplate>
<td>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px">
<tr>
<td>
<span>
<%# Eval("Id") %>
</span>
</td>
</tr>
<tr>
<td>
Name: <span><%# Eval("Field_name_of_your_DB") %></span><br />
Number: <span><%# Eval("Field_name_of_your_DB") %></span><br />
Date: <span><%# Eval("Field_name_of_your_DB", "{0:MM dd, yyyy}") %></span><br />
Comment: <span><%# Eval("Field_name_of_your_DB") %></span><br />
</td>
</tr>
</table>
</td>
</ItemTemplate>
</asp:ListView>
And, be sure that autogeneratecolumn = false to avoid displaying data twice.

How to get the selected DDL value from a row in ListView

right now I am just trying to put together a simple role assigning pages in ASP.NET, I have created a listview, and in my item template I have a drop down list, with a button in the same template. The DDL is hooked up to an ODS which gets me the current roles, and I have a method which will take the role and the username, and assign that user to a specific role. My code is as follows:
<h2>Users</h2>
<asp:ListView ID="UserListView" runat="server"
ItemType="Synergy_System.Entities.Security.ApplicationUser"
OnItemCommand="UserListView_ItemCommand">
<EmptyDataTemplate>
<table runat="server">
<tr>
<td>
No users in this site.
<asp:LinkButton runat="server" CommandName="AddUsers" Text="Add users" ID="AddUsersButton" />
</td>
</tr>
</table>
</EmptyDataTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label Text='<%# Item.UserName %>' runat="server" ID="UserNameLabel" /></td>
<td>
<asp:Label Text='<%# Item.Email %>' runat="server" ID="EmailLabel" /></td>
<td><em>password is hashed</em></td>
<td>
<asp:DropDownList ID="RolesList" runat="server" DataSourceID="RoleListODS" DataTextField="Name" DataValueField="Name">
</asp:DropDownList>
<asp:Button ID="AddRoleToUser" runat="server" Text="Add Role" onclick="AddRoleToUser_Click" />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table runat="server" id="itemPlaceholderContainer"
class="table table-condensed table-hover table-striped">
<tr runat="server">
<th runat="server">User Name</th>
<th runat="server">Email</th>
<th runat="server">Password</th>
<th runat="server">Roles</th>
</tr>
<tr runat="server" id="itemPlaceholder"></tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server">
<asp:DataPager runat="server" ID="DataPager1">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True"></asp:NextPreviousPagerField>
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
I have code behind pretty much empty, as it's just like this right now:
protected void AddRoleToUser_Click(object sender, EventArgs e)
{
string username;
string role;
//get username
//get value from DDL
UserManager.AddUserToRole(username,role);
}
I have used GridViews before but haven't dealt with ListViews much. I just want it so that when I click the button in that particular row, i retrieve this information, but there is no .Row in a listview.... any help would be greatly appreciated.
You can Use CommandName property of Button
<asp:Button ID="AddRoleToUser" CommandName="AddRole"
Code Behind
protected void UserListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (String.Equals(e.CommandName, "AddRole"))
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
// this will gives you Row for your list items
Label UserNameLabel=(Label)dataItem.FindControl("UserNameLabel");
// you can find any control on row like this
string YourNameLabel=UserNameLabel.Text;
}
}

How to copy an aspx ListView from the aspx.cs file?

How do I copy an .aspx ListView (including it's LayoutTemplate and ItemTemplate) from the aspx.cs file? The .aspx.cs uses DataBind() to display the values onto the page.
so essentially I want to turn this:
<asp:ListView ID="EvalAnswerList" OnItemDataBound="EvalAnswerList_ItemDataBound" runat="server">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" runat="server" class="altRows" id="tblProducts">
<tr id="Tr1" runat="server">
<th id="Th1" runat="server">Question
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id="Tr2" runat="server">
<td>
<asp:Label ID="QuestionTextLabel" Font-Bold="true" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Into this:
<asp:ListView ID="EvalAnswerList" OnItemDataBound="EvalAnswerList_ItemDataBound" runat="server">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" runat="server" class="altRows" id="tblProducts">
<tr id="Tr1" runat="server">
<th id="Th1" runat="server">Question
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id="Tr2" runat="server">
<td>
<asp:Label ID="QuestionTextLabel" Font-Bold="true" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:ListView ID="EvalAnswerList" OnItemDataBound="EvalAnswerList_ItemDataBound" runat="server">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" runat="server" class="altRows" id="tblProducts">
<tr id="Tr1" runat="server">
<th id="Th1" runat="server">Question
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id="Tr2" runat="server">
<td>
<asp:Label ID="QuestionTextLabel" Font-Bold="true" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
This copying has to be done in the aspx.cs file. Obviously it won't be exactly like this but I wanted to give you an idea of what I am trying to do.
I've tried saying:
ListView test = new ListView();
PlaceHolder.Controls.Add(test);
test = EvalAnswerList;
and then trying to use this in the test.DataBind() but it won't work.
You can use a webusercontrol, try below steps
Step 1: Create a usercontrol and put your list view in that
<%# Control Language="C#" AutoEventWireup="true" CodeFile="CustomListView.ascx.cs"
Inherits="CustomListView" %>
<asp:ListView ID="EvalAnswerList" OnItemDataBound="EvalAnswerList_ItemDataBound"
runat="server">
<layouttemplate>
<table cellpadding="2" width="640px" border="1" runat="server" class="altRows" id="tblProducts">
<tr id="Tr1" runat="server">
<th id="Th1" runat="server">Question
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</layouttemplate>
<itemtemplate>
<tr id="Tr2" runat="server">
<td>
<asp:Label ID="QuestionTextLabel" Font-Bold="true" runat="server" />
</td>
</tr>
</itemtemplate>
</asp:ListView>
enter code here
Setp 2: Create a public DataSet/DataTable to bind listview in page load
public DataSet dsSource = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EvalAnswerList.DataSource = dsSource;
EvalAnswerList.DataBind();
}
}
enter code here
Step 3: Now add reference to usercontrol in your aspx page
<%# Reference Control="CustomListView.ascx" %>
enter code here
Step 4: At last, now you can use that list view multiple times in you aspx. Take a panel or div, then add usercontrol to where you want.
CustomListView clv = new CustomListView();
clv.dsSource = ds;//dataset/datatable to bind listview
div.Controls.Add(clv);
gud luck!
In the end, I used a repeater control and it worked. Thanks!

Repeater control with nested elements TR TD

I want to show my data in the format like below:
<table>
<tr>
<td></td>
<td></td>
<td></td>
...
</tr>
<tr>
<td></td>
<td></td>
<td></td>
...
</tr>
.
.
.
</table>
I am bit confused about how to represent the data.
I am thinking to use the repeater control for this structure. But will it need a nested repeater control or it can be done using the single repeater control?
Can anybody please suggest me the proper way?
Thanks in advance.
Update :: In my case and are not in static order they are fully dynamic.In some cases may have the single but in some case they me be 10-20 in count.I need to show the score for test in those structure.for example:
<table>
<tr>
<td>10</td>
<td>5</td>
<td>30</td>
</tr>
<tr>
<td>40</td>
<td>34</td>
</tr>
.
.
.
<table>
like wise.In simple word when the score record for one user is completed I need to add new record in the new fresh .
Why are you using repeater? It's rather obsolete component. Use ListView instead. It's much more flexible in configuration and manipulation.
Please use solution suggested here by Merrimack
<asp:ListView ID="myListView" runat="server"
DataSourceID="YOURDATASOURCE" GroupItemCount="3">
<LayoutTemplate>
<table>
<tr>
<td>
<table border="0" cellpadding="5">
<asp:PlaceHolder runat="server" ID="groupPlaceHolder"></asp:PlaceHolder>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder"></asp:PlaceHolder>
</tr>
</GroupTemplate>
<ItemTemplate>
<td>
<%# Eval("FullName") %>
</td>
</ItemTemplate>
</asp:ListView>
One solution from Old Classic way is nested loop
<table>
<% for(int loop1 = 0; loop1 <= condition1 ; loop1++){
System.Console.WriteLine("<tr>");
for(int loop2 = 0; loop2 <= condition2 ; loop2++){
System.Console.WriteLine("<td>");
System.Console.WriteLine("Your Data");
System.Console.WriteLine("</td>");
}
System.Console.WriteLine("</tr>");
} %>
</table>
You could make a Repeater like this
<asp:Repeater ID="rptMyRepeater" runat="server" >
<HeaderTemplate>
<table>
<th>
<td>
Header 1
</td>
<td>
Header 2
</td>
</th>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HiddenField runat="server" ID="hfHolderId" Value='<%# DataBinder.Eval(Container.DataItem, "HolderId") %>' />
<asp:TextBox runat="server" ID="tbText1" Text='<%# DataBinder.Eval(Container.DataItem, "Text1") %>' />
</td>
<td>
<asp:TextBox runat="server" ID="tbText2" Text='<%# DataBinder.Eval(Container.DataItem, "Text2") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Then have a class to hold your data
public class MyHolder()
{
public string HolderId {get;set;}
public string Text1 {get;set;}
public string Text2 {get;set;}
}
Then make a list of these and bind them to your Repeater
List<MyHolder> myHolderList = new List<MyHolder>();
myHolderList.Add(new MyHolder {1, "hi", "hello"});
//Add a few of these
rptrptMyRepeater.DataSource = myHolderList;
rptMyRepeater.DataBind();
All this was just outta my head so there my be syntax errors in there
I finally done this with the dynamic table in asp.net.Like RDSAGAR did,but by code behind.Thanks for all your support.

Categories