Compare two tables in asp.net - c#

I'm making a website to show various statistics regarding games.
I got two seperate tables in an sql-database. One called PlayerMatch and another called Match.
The two columns I want to compare is TeamId in PlayerMatch (PlayerMatch.TeamId vs. WinningTeamId in Match (Match.WinningTeamId)
To show it all, I have made a table, where I have placed some asp:repeaters inside.
Here is one of them, as they are all essentially the same.
<asp:Repeater ID="repHighGPM" runat="server">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%#Eval("Match.WinningTeamId") %></td>
<td><%#Eval("Name") %></td>
<td>
<img src=' <%#Eval("Image") %>' /></td>
<td><%#Eval("GoldPerMinute") %></td>
</ItemTemplate>
</asp:Repeater>
Now, the problem is that as it is now it will only show the Id of the team who won (Match.WinningTeamId). But not if the player was on that team. So essentially it just needs to check if PlayerMatch.TeamId == Match.WinningTeamId. And if that is true it should write "won match", while false will be "lost match"
Any ideas? I know it should be some kind of if-else function, but I have no idea how to do it.

You could use the inner join in sql query :
make a datasource to your databse write the query after that add the datasource to repeater DataSourceID="" ....
<asp:Repeater ID="repHighGPM" runat="server" DataSourceID="match">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%#Eval("Match.WinningTeamId") %></td>
<td><%#Eval("Name") %></td>
<td>
<img src=' <%#Eval("Image") %>' /></td>
<td><%#Eval("GoldPerMinute") %></td>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="match" runat="server" ConnectionString="<%$ ConnectionStrings:database %>" SelectCommand="select m.match number, m.winningTeamID, Name ,Image from Match m inner join
playermatch p on p.Teamid = m.WinningTeamId"></asp:SqlDataSource>
for more information about inner join read this article :
http://www.w3schools.com/sql/sql_join_inner.asp

I have solved the problem with the following solution:
public string MatchResult (object Result) {
int id = Convert.ToInt32(Request.QueryString["id"]);
DOTA2DataContext db = new DOTA2DataContext();
var Victory = Result;
var TeamId = db.PlayerMatches.Where(x => x.TeamId == id);
var WinningTeam = db.Matches.Where(x => x.WinningTeamId == id);
{
if (TeamId == WinningTeam)
{
return "Won match";
}
else
{
return "Lost match";
}
}
}
And the repeater.
<asp:Repeater ID="repHighD" runat="server">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%# MatchResult(Eval("Match.WinningTeamId"))%></td>
<td><%#Eval("Hero.Name") %></td>
<td>
<img src=' <%#Eval("Hero.Image") %>' /></td>
<td><%#Eval("Denies") %></td>
</ItemTemplate>
</asp:Repeater>

Related

How to return asp:repeater count

I have searching implemented in my app, and it goes to a results page where the results populate a table through an asp:repeater. I'll include the code below.
C#
namespace WebApplication {
public partial class SearchResults : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (Request.Params["searchterm"] != null) {
ResultLabel.Text = "Search results for: " + Request.Params["searchterm"];
string searchTerm = Request.Params["searchterm"];
int results = 0; //If I were to set it on back end
string constr = ConfigurationManager.ConnectionStrings["CurrencyDb"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr)) {
using (SqlCommand cmd = new SqlCommand("dbo.SearchProc", con)) {
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SearchTerm", searchTerm);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
ResultsTableRepeater.DataSource = ds;
ResultsTableRepeater.DataBind();
}
catch (SqlException sqlex) {
throw new Exception("SQL Exception loading data from database. " + sqlex.Message);
}
catch (Exception ex) {
throw new Exception("Error loading results data from database. " + ex.Message);
}
}
}
}
}
}
}
asp.net
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<br />
<br />
<br />
<br />
<asp:Label ID="ResultLabel" runat="server"></asp:Label>
<br />
<br />
<br />
<br />
<asp:Repeater ID="ResultsTableRepeater" runat="server">
<HeaderTemplate>
<table class="td-table-bordered">
<th>Currency Id</th>
<th>Component</th>
<th>Version</th>
<th>Vendor</th>
<th>Tech Owner</th>
<th>Tech Contact</th>
<th>Fiscal Consideration</th>
<th>Currency Status</th>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("CurrencyId") %></td>
<td><asp:HyperLink ID="UpdateLink" NavigateUrl='<%# Eval("CurrencyId", "http://10.155.54.101/Update?CurrencyId={0}") %>' runat="server" Target="_blank"><%# Eval("Model") %></asp:HyperLink></td>
<td><%# Eval("Version") %></td>
<td><%# Eval("Vendor") %></td>
<td><%# Eval("Tech Owner") %></td>
<td><%# Eval("Tech Contact") %></td>
<td><%# Eval("FiscalConsideration") %></td>
<td><%# Eval("Status") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<asp:Label ID="StatusLabel" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
</asp:Repeater>
<br />
</asp:Content>
What I would like to do is print a number how many results were returned in the footer. But I can't seem to find a way to do that throughout all of my searching, despite it seeming like it should be a simple task.
Is there a way, whether it be in the C# code behind or in the aspx directly to print how the amount of results at the end? It would be easy if there were a while(reader.read) loop to increment a counter, however that's not the case.
Thanks in advance so much for your help!
You can use the return value of sda.Fill(ds);:
As the documentation for Fill says:
Return Value: The number of rows successfully added to or refreshed in the DataSet.
Thus:
int rowsReturned = sda.Fill(ds);
Then you can assign the value in the footer.
Here is a similar issue here:
Determine the repeater row count in asp.net
Hope this helps you out! Should just be able to use their solution anywhere in your codebehind to get the Count, and then display it where ever you need it in your footer (assuming your repeater is already populated when you try to get the count).

ASP.NET ListView Elements Display <#Eval?

I've got a ListView control that uses a custom data source. It will be a database soon, but for now I am still trying to get it running.
In the HTML of my form, I have the following code:
<%-- Ref: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.layouttemplate.aspx --%>
<asp:ListView ID="lvOfficers" runat="server"
OnSelectedIndexChanging="lvOfficers_SelectedIndexChanging"
OnSelectedIndexChanged="lvOfficers_SelectedIndexChanged">
<LayoutTemplate>
<table id="tblOfficers">
<tr>
<th style="width:20%"></th>
<th colspan="2">Member Name</th>
<th style="width:20%"></th>
<th style="width:20%"></th>
</tr>
<tr>
<th>Title</th>
<th>Last</th>
<th>First</th>
<th>Phone</th>
<th>Email</th>
</tr>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:Label ID="lblRank" runat="server" Text='<#Eval("Rank") %>'></asp:Label></td>
<td><asp:Label ID="lblLast" runat="server" Text='<#Eval("LastName") %>'></asp:Label></td>
<td><asp:Label ID="lblFirst" runat="server" Text='<#Eval("FirstName") %>'></asp:Label></td>
<td><asp:Label ID="lblPhone" runat="server" Text='<#Eval("HomePhone") %>'></asp:Label></td>
<td><asp:Label ID="lblEmail1" runat="server" Text='<#Eval("PersonalEmail") %>'></asp:Label></td>
</tr>
</ItemTemplate>
</asp:ListView>
In the code behind with the Page_Load, I populate the data:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
GetOfficers();
}
}
protected void GetOfficers() {
lvOfficers.DataSource = Personnel.GetOfficers();
lvOfficers.DataBind();
}
I can step through in Debug mode and see that there are 8 elements of type Person in a ListView that my "GetOfficers" data factory churns out.
The Person class contains subclasses:
Phone class: for {Home, Cell, Work},
Address class {Primary, Secondary} that contain ranking logic to indicate contact methods, and
Membership class. One tracks a member's ID, JoinDate, and Expiration while a second instance tracks the same elements for LifeMembership.
Thinking this complex Person class was causing my problems, I edited the GetOfficers() method to use an anonymous list:
protected void GetOfficers() {
var officers = Personnel.GetOfficers();
var data = from o in officers
select new {
o.Rank,
o.LastName,
o.FirstName,
o.HomePhone,
o.PersonalEmail,
};
//var data = (from o in officers
// select new {
// o.Rank,
// o.LastName,
// o.FirstName,
// o.HomePhone,
// o.PersonalEmail,
// }).OrderBy(o => o.Rank).OrderBy(o => o.LastName);
lvOfficers.DataSource = data;
lvOfficers.DataBind();
}
I was pretty sure that was going to solve my problems at first, so I included the two OrderBy clauses. When it did not work, I commented it out to try again, but I still got no success.
No matter what I seem to try, the page displays with the "Eval" text showing instead of the actual data.
I'm guessing the answer is something simple that I am overlooking because I use this same technique to populate the data in other pages in the same project.
How do I get my data to show up?
You need % at the start like this:-
'<%# Eval("Rank") %>'
you need to add % sign at the start of eval
'<%#Eval("FieldName")%>'

NavigateUrl on Repeater ASP.net

I have a table in DB:
NOTICE(NUM,TITLE,CONTENT)
I use Repeater Control in ASP to show all the notices in DB, like:
+----------+------------+|
|title1 (readmore)|
|
|title2 (readmore)|
|
|title3 (readmore)|
......
+------------------------+
All I want is: I read a "title" then I clicked on (readmore), the new page will be opened ( show detail's notice) with the "content" of that notice. How can I assign the num of notice without display it to define the notice in next page?
I just assign the title to property Text of a Label ID="TITLE" because I want to show the title of each notice.
All information I want to show in the this page is: title and the readmore( link to the next page). So that I don't know how to assign the num
My asp page: notice.asp
<asp:Repeater ID="RepDetails" runat="server" >
<HeaderTemplate>
<table style=" width:565px" cellpadding="0" class="borber">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Title" runat="server" Text='<%#Eval("TITLE") %>' />
</td>
<td>
<asp:HyperLink ID="HyperLink1" runat="server" > (readmord)</asp:HyperLink>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
My C# code:notice.asp.cs
private void BindRepeaterData()
{
string sql = "select num,title from NOTICE";
DataTable ds = l.EXECUTEQUERYSQL(sql);
RepDetails.DataSource = ds;
RepDetails.DataBind();
}
And the next page: detailnotice.asp.cs
private void GetNotice()
{
string sql = "select * from NOTICE where num=" ;// num= the num of notice I choose in notice.asp page.
}
How can I assign a num in Label without display it? What property of Label Control or I should use a other Control ?
Hope you understand what I say. If you don't, please ask?
Basically the same as Sain but using the NavigateURL
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("NUM","~/detailpage.aspx?id={0}") %>' > (readmord)</asp:HyperLink>
hi you can ues anchor tag in place of hyper link button. you can pass num in the query string to the detail page.
<a href='detailpage.aspx?id=<%#Eval("NUM") %>'> (readmord)</a>
On details page you can get query string value and fetch details from database.
int myKey = 0;
if (!string.IsNullOrEmpty(Request.QueryString["id"]))
{
myKey = int.Parse(Request.QueryString["id"]);
// Use myKey to retrieve record from database
}

asp:repeater show count of items in each category

I have a simple repeater that gets the 'groups' of 'widgets' The home page lists all of the groups:
<ItemTemplate>
<tr>
<td width="60" class="center"><%# DataBinder.Eval(Container.DataItem, "Number") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Name") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Description") %></td>
</tr>
</ItemTemplate>
Code Behind
private void LoadForm()
{
using (MarketingWebContentEntities context = new MarketingWebContentEntities())
{
rptGroup.DataSource = (from groups in context.URLGroup
select groups).ToList();
rptGroup.DataBind();
}
}
I would like within the repeater to show number of 'widgets' within each 'group'. I know I'd need to run a query on the 'widgets' table to see how many items are in that list. I'm just unsure how to add that within the repeater mark-up.
As mentioned in the comment, you could use the ItemDataBound event for this.
This example is in VB - been a while since I wrote C#, though will give you an idea. I haven't checked it for syntax either, it's more an example to get you up and running.
In your <ItemTemplate> add yourself, say, a ASP:Label. In this case, it's called myLabel
So in your code behind, create a private method that will handle the ItemDataBound event.
Protected Sub myRepeater_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles myRepeater.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim uG As URLGroup = CType(e.Item.DataItem, URLGroup)
'' you now have the group for that one item
'' you should now be able to get additional information needed.
'' you can also get the myLabel from this item
dim lbl as Label = CType(e.Item.FindControl("myLabel", Label)
'' and set its text to whatever you need
lbl.Text = MyCounter
End If
End Sub
Hopefully this will get you on your way.
Here is a link to the MSDN documentation for it too.
I used the OnItemDataBount event
<asp:Repeater runat="server" ID="rptGroup" OnItemDataBound="rptDestinationCount_ItemDataBound">
<HeaderTemplate>
<table id="tblUrlGroup" class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Name</th>
<th style="width:20px;">Count</th>
<th style="width:35px;">Add</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><i class="icon-wrench" rel="tooltip" title="Edit Group Name"></i> <%# DataBinder.Eval(Container.DataItem, "Name") %></td>
<td class="center"><asp:HiddenField runat="server" ID="hidURLGroupRowID" Value='<%# DataBinder.Eval(Container.DataItem, "URLGroupRowID") %>' /><asp:Label runat="server" ID="lblCount"></asp:Label></td>
<td class="center">
<i class="icon-plus" rel="tooltip" title="Manage Destination URLs"></i>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
On the function I made sure I was only looking through the repeater Item and Item Template. The hidden field is set with the ID with the datasource. This allowed me to run a query and set the lblCount.Text to the destination count.
Code Behind
protected void rptDestinationCount_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
using (MarketingWebContentEntities context = new MarketingWebContentEntities())
{
Label lblCount = (Label)e.Item.FindControl("lblCount");
HiddenField hidURLGroupRowID = (HiddenField)e.Item.FindControl("hidURLGroupRowID");
int groupRowID = Convert.ToInt32(hidURLGroupRowID.Value);
var destination = (from dest in context.URLDestination
where dest.URLGroup.URLGroupRowID == groupRowID
select dest).ToList();
lblCount.Text = destination.Count.ToString();
}
}
}

Repeater in Repeater Databinding (no postback)

For the solution, I cannot use any postback methods, because this is all working through ajax. The solution need to be implemented in the asp.net code.
I have a List<WebPage> that contains a list of Links (List<Link>) and I need for all the links to bind repetitive information such as page title, id, url. Here is my current repeater.
<div id="result">
<asp:Repeater runat="server" id="results">
<Itemtemplate>
<asp:Repeater runat="server" datasource='<%# Eval("Links") %>'>
<Itemtemplate>
<tr class="gradeX odd">
<td><%# Eval("Id") %></td> //property of WebPage (part of results repeater)
<td><%# Eval("Title") %></td> //property of WebPage (part of results repeater)
<td><%# Eval("Url") %></td> //property of WebPage (part of results repeater)
<td><%# Eval("URL") %></td>//Property of Link
<td><%# Eval("URLType") %></td> //Property of Link
<td><%# Eval("URLState") %></td> //Property of Link
</tr>
</Itemtemplate>
</asp:Repeater>
</Itemtemplate>
</asp:Repeater>
</div>
of course this doesnt work, how can i do this?
Thanks for your help!
I'm assuming the problem you're trying to solve here is how to include properties from multiple levels in a nested object-- some properties from the top level but other properties from the lower level. One easy way to do this is to transform the inner collection into a new type which contains a mix of all the properties you need.
Here's a code sample illustrating this technique using IEnumerable.Select and C# Anonymous Classes to create a new class:
<%# Page Title="Home Page" Language="C#" %>
<div id="result">
<asp:Repeater runat="server" id="results">
<ItemTemplate>
<asp:Repeater runat="server" datasource='<%# ((WebPage)Container.DataItem).Links.Select ( link => new {
Id = ((WebPage)Container.DataItem).Id,
Title = ((WebPage)Container.DataItem).Title,
Url = ((WebPage)Container.DataItem).Url,
URL = link.URL,
URLType = link.URLType,
URLState = link.URLState
}) %>'>
<ItemTemplate>
<tr class="gradeX odd">
<td><%# Eval("Id") %></td> <!--property of WebPage (part of results repeater) -->
<td><%# Eval("Title") %></td> <!--property of WebPage (part of results repeater) -->
<td><%# Eval("Url") %></td> <!--property of WebPage (part of results repeater) -->
<td><%# Eval("URL") %></td><!--Property of Link -->
<td><%# Eval("URLType") %></td> <!--Property of Link-->
<td><%# Eval("URLState") %></td> <!--Property of Link -->
</tr>
</ItemTemplate>
</asp:Repeater>
</Itemtemplate>
</asp:Repeater>
</div>
<script runat="server">
public class Link
{
public string URL { get; set; }
public int URLType { get; set; }
public int URLState { get; set; }
}
public class WebPage
{
public string Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public List<Link> Links { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
WebPage[] pages = new WebPage[]
{
new WebPage { Id = "foo",
Title = "foobar",
Url = "http://foo.bar",
Links = new List<Link> ( new Link[] {
new Link {URL = "http://something", URLType = 1, URLState = 2},
new Link {URL = "http://someotherthing", URLType = 3, URLState = 4}
})
},
new WebPage { Id = "excellent",
Title = "excellent Title",
Url = "http://excellent.com",
Links = new List<Link> ( new Link[] {
new Link {URL = "http://excellent", URLType = 5, URLState = 6},
new Link {URL = "http://totallyexcellent", URLType = 7, URLState = 8}
})
}
};
results.DataSource = pages;
results.DataBind();
}
</script>

Categories

Resources