How to use different style for the first item in repeater? - asp.net

For first item I want to use the following <div>:
<div class="six columns">
<a href="">
<img src="" />
<h3>Israeli Embassy Promotes Peace</h3>
<h4>At a time when Israel is facing threats of...</h4>
</a>
</div>
And This for rest i want to use following <div>:
<div class="six columns">
<ul>
<li><a href="">
<h3>This is the first alskdjlak s</h3>
</a></li>
<li><a href="">
<h3>asd sad asd asd asdasdasdas d</h3>
</a></li>
<li><a href="">
<h3>dsad asd asd asd asd asd asd</h3>
</a></li>
</ul>
</div>
How do i do it?

You first use one integer on the code behind, that is start with 1.
Then on repeater you check this value and you go like:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<% if (iCounter == 1) { %>
<br />First line id: <%# GetID(Container.DataItem) %>
<% } else { %>
<br />Next lines id: <%# GetID(Container.DataItem) %>
<% }
iCounter++;
%>
</ItemTemplate>
</asp:Repeater>
and on code behind:
public int iCounter = 1;
List<int> oMainIds = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
oMainIds.Add(i);
}
Repeater1.DataSource = oMainIds;
Repeater1.DataBind();
}
public int GetID(object oItem)
{
return (int)oItem;
}
Please note, for the test, here I place and 10 data lines. This example renders:
First line id: 0
Next lines id: 1
Next lines id: 2
Next lines id: 3
Next lines id: 4
Next lines id: 5
Next lines id: 6
Next lines id: 7
Next lines id: 8
Next lines id: 9

Just an update to Aristos answer, without the code-behind method to get the ID.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Panel ID="pnlFirst" runat="server" Visible="<%# (Repeater1.DataSource as List<int>).IndexOf((int)Container.DataItem) ==0 %>">
<br />First Item
</asp:Panel>
<asp:Panel ID="pnlRest" runat="server" Visible="<%# (Repeater1.DataSource as List<int>).IndexOf((int)Container.DataItem) !=0 %>">
<br />
Item: <%# (Repeater1.DataSource as List<int>).IndexOf((int)Container.DataItem) %>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
and in code behind
List<int> oMainIds = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
oMainIds.Add(i);
}
Repeater1.DataSource = oMainIds;
Repeater1.DataBind();
}

Wrap your divs in PlaceHolder controls, and set the visibility of the PlaceHolders in the OnItemCreated event of the repeater using e.Item.ItemIndex to determine if the current item is the first one or not.
Or make them server-side divs (with runat=server) and set the visibility of the divs directly in the sme way

Use CSS.
.six_columns ul li
{
/* Item style */
}
.six_columns ul li:first-child
{
/* First item style */
}
There are also methods for editing content via CSS.

Related

how to call a back method from front asp.net

I'm trying to call a method written in the back from a div in the front
front:
<div runat="server" id="headerLink" onclick="headerLinkOnClick" style="cursor: pointer;">
<header>
</header>
</div>
back:
protected void headerLinkOnClick(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
Response.Redirect("~/default.aspx");
}
I must miss something but no idea what.
You can achieve this with a hidden button
<asp:Button runat="server" id="btnPostback" style="display:none" onclick="headerLinkOnClick" />
<div onclick="document.getElementById('<%= btnPostback.ClientID %>').click()">Clickable DIV</div>

Is it possible to auto increment repeater control?

I have a repeater control on my web page that displays images as a result of a search. The user searches for a keyword, and my program stores the search results in a data table. The repeater then displays the images in the data table. So, if there are 150 images in the data table, the repeater will display all 150 images. Here's the code for my repeater:
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="background-color: Silver; border-style: solid; display: inline-block;
float: left; margin: 5px; overflow: hidden;">
<div style="text-align: center">
<asp:Label ID="lblImage" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "image") %>'></asp:Label>
</div>
<div>
<%# DataBinder.Eval(Container.DataItem, "url") %>
</div>
<div style="text-align: center;">
<asp:HyperLink ID="requestLink" runat="server" Text="Original" NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "requestUrl") %>'>
</asp:HyperLink>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
What if, however, I don't want to display all 150 images? Is there a way to only display, say, 20 at a time and let the repeater auto expand when the user scrolls down or hits a 'MORE' button, or something like that?
Thanks!
For that you have to search for auto refresh or scroll event of mouse.
for auto refresh you can write this kind of code in javascript using that you can reload page after every interval
<script type="text/javascript">
setInterval(function () {
load()
}, 30000);
var load = function () {
location.reload();
};
</script>
and on Load event of page you have to rebind data to repeater.

Images not enlarging on click in asp.net

In my page I have a large image and set of small unit images. the large image will be loaded on page load. but when i click on small images it will get enlarge and get displayed in place of large image. the small images are displaying on page . but it has no effect on clicking them
here is my code
<div class="invDetailImage">
<img id="imgenlarge" src="" runat="server" alt="" align="middle" style="max-height:380px; max-width:579px; vertical-align:middle;"/>
<asp:Label runat="server" ID="lblerr" Visible="false" style="max-height:380px; max-width:579px; vertical-align:middle;font-size:large;"></asp:Label>
</div>
<!-- SMALL IMAGES -->
<div class="invDetailPhotoBox" runat="server" id="photobox">
<asp:Label runat="server" ID="lblphotos" Text="Select a photo below to view in the window above:"></asp:Label><br />
<asp:Repeater runat="server" ID="rptrinventoryphotos" onitemdatabound="rptrinventoryphotos_ItemDataBound">
<ItemTemplate>
<img id="imgInventory" src="" runat="server" alt='<%#Eval("ImagePath")%>' style="display:none;" />
<div onclick="large('<%#Eval("ImagePath")%>')" style="float:left;clear:none; margin-left:-12px;">
<asp:Image ID="Image1" Visible="true" runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<script type="text/javascript"> function large(src) {
var str=src; document.getElementById("ctl00_ContentPlaceHolder1_imgenlarge").src = (str);
}
function loading(img) { img.src = "images/loading.gif"; }
</script>
protected void rptrinventoryphotos_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
HtmlImage img1 =(HtmlImage) e.Item.FindControl("imgInventory");
Image img = (Image)e.Item.FindControl("Image1");
img.ImageUrl = "http://localhost:22525/DWLive/ImageResizeHandler.ashx?imgPath=" + img1.Alt + "&width=75&height=56";
img.Style.Add("margin-left", "-12px");
img.Style.Add("background-image", "url('images/loading9.gif')");
img.Style.Add("background-repeat", "no-repeat");
img.Style.Add("background-position", "center left");
//img.Attributes.Add("onclick", "large('" + img1.Alt + "')");
string[] a = img1.Alt.Split((#"/").ToCharArray());
}
can anyone help please? thanks.
The problem was in JavaScript. I changed it to:
<script type="text/javascript">
function large(link) {
var str = link;
}
document.getElementById("ctl00_ContentPlaceHolder1_imgenlarge").src = (str);

ASP.NET group data by month

I wish to group some data by month (stored in an SQL Database), with collapsible DIVs, no doubt with jQuery. I don't particularly want to use to GridView, as I'd like to stay away from tables for simplicity when writing the jQuery.
What is the best method to do this in ASP.NET, which control would I use?
Please see the following example, for an idea of what I am trying to describe:
I've created a project which displays data by month using nested repeaters, it's uploaded on Google Docs (just click File->Save to download the .zip).
Here's a brief overview of how it works:
Assuming you have a simple Orders table in the db with the following columns
OrderId
Product
Quantity
DateOfSale
Process
Execute a stored procedure to get the months for a given year (I used EntityFramework functions, you could change this to ADO.NET,LINQ etc)
Bind the returned months to a label in the master repeater(These will be your headings)
Handle the OnItemDataBound event of the master repeater, this event runs every time an item is bound to the repeater.
Inside OnItemDataBound execute a stored procedure to get all the records for the specific month and year and simply bind the returned data to the child repeater
Add little jQuery to show and hide divs and you're set.
Code
Stored procedures:
CREATE PROCEDURE dbo.GetMonthsByYear
#Year INT
AS
BEGIN
SELECT DISTINCT DATENAME(Month,DateOfSale) AS [Month] FROM Orders
WHERE Year(DateOfSale) = #Year
END
CREATE PROCEDURE dbo.GetOrdersByMonth
#Month NVARCHAR(15),
#Year INT
AS
BEGIN
SELECT * FROM Orders
WHERE (Year(DateOfSale) = #Year) AND DATENAME(MONTH,DateOfSale) = #Month
END
ASPX:
<head runat="server">
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
var showHide;
$(document).ready(function () {
showHide = function (control) {
var parent = $(control).next();
var display = parent.css('display');
if (display == "none") { parent.fadeIn('slow'); }
else { parent.fadeOut('slow'); }
};
});
</script>
<style type="text/css">
.detail
{
height:300px;
display:none;
width: 100%;
border: 1px solid black;
}
.header
{
vertical-align: top;
padding: 3px;
height: 30px;
background: black;
color: White;
font-weight: bold;
}
</style>
<title>Nested Repeater</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Select year: <asp:TextBox ID="txtYear" runat="server" /><br />
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="Search" /><br />
<asp:Repeater ID="masterRepeater" runat="server" OnItemDataBound="ItemDataBound">
<ItemTemplate>
<div id='<%# Container.DataItem %>' class="header" onclick="showHide(this);">
<asp:Label ID="lblMonth" runat="server" Text='<%# Container.DataItem %>' />
</div>
<div class="detail">
<asp:Repeater ID="detailRepeater" runat="server">
<HeaderTemplate>
<span style="text-decoration: underline">Product</span><br />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Product") %>' />
<asp:Label ID="lblQuantity" runat="server" Text='<%# Bind("Quantity") %>' />
<asp:Label ID="lblDateOfSale" runat="server" Text='<%# Bind("DateOfSale") %>' /><br />
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
Code behind:
protected void Search(object sender, EventArgs e)
{
int year = 0;
if (Int32.TryParse(txtYear.Text, out year))
{
orderEntities orders = new orderEntities();
List<string> months = orders.GetMonthByYear(year).ToList();
masterRepeater.DataSource = months;
masterRepeater.DataBind();
}
}
protected void ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
int year = 0;
if (Int32.TryParse(txtYear.Text, out year))
{
Label lblMonth = e.Item.FindControl("lblMonth") as Label;
if (lblMonth != null)
{
string month = lblMonth.Text;
Repeater detailRepeater = e.Item.FindControl("detailRepeater") as Repeater;
if (detailRepeater != null)
{
orderEntities orders = new orderEntities();
var ordersByMonth = orders.GetOrdersByMonth(month, year).ToList();
detailRepeater.DataSource = ordersByMonth;
detailRepeater.DataBind();
}
}
}
}
}
Result:

Gridview column color doesnt fill entire box

I have a gridview with certain boxes that are highlighted in green. These boxes should fill the entire box, but I can't seem to trash this 1px border around the edges. I'm using IE7, but FF does it too.
Rendered html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title><link href="Style/StyleSheet.css" rel="stylesheet" type="text/css" /><link href="App_Themes/Contoso/Style.css" type="text/css" rel="stylesheet" /></head>
<body>
<form name="form1" method="post" action="GridViewColoring.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODIyMTgxMzQxZBgBBQh0ZXN0R3JpZA88KwAMAQgCAWR6Qz5BuXEoalr4HjsTfYqqKPrdwd2ICIXpeNacwdi46w==" />
</div>
<div>
<div>
<table class="cssTable" cellspacing="0" rules="all" border="1" id="testGrid" style="border-collapse:collapse;">
<tr>
<th scope="col">Description</th><th scope="col">Serial#</th>
</tr><tr style="background-color:Yellow;">
<td class="NoMargin NoPadding" style="font-size:Smaller;">
<span id="testGrid_ctl02_descriptionLbl">Some desc 1/25/2011 9:51:27 AM</span>
</td><td style="font-size:Smaller;">
<span id="testGrid_ctl02_serialNumberLbl" class="NoMargin NoPadding MaxHeightAndWidth NoBorder" style="display:inline-block;height:100%;width:100%;">0</span>
</td>
</tr><tr style="background-color:Yellow;">
<td class="NoMargin NoPadding" style="font-size:Smaller;">
<span id="testGrid_ctl03_descriptionLbl">Some desc 1/25/2011 9:51:27 AM</span>
</td><td style="font-size:Smaller;">
<span id="testGrid_ctl03_serialNumberLbl" class="NoMargin NoPadding MaxHeightAndWidth NoBorder" style="display:inline-block;background-color:#CCFFCC;height:100%;width:100%;">1000</span>
</td>
</tr><tr style="background-color:Yellow;">
<td class="NoMargin NoPadding" style="font-size:Smaller;">
<span id="testGrid_ctl04_descriptionLbl">Some desc 1/25/2011 9:51:27 AM</span>
</td><td style="font-size:Smaller;">
<span id="testGrid_ctl04_serialNumberLbl" class="NoMargin NoPadding MaxHeightAndWidth NoBorder" style="display:inline-block;background-color:#CCFFCC;height:100%;width:100%;">2000</span>
</td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
test case
CSS
body {
}
.NoMargin
{
margin:0 0 0 0;
}
.NoPadding
{
padding:0 0 0 0;
}
.BgColor
{
background-color:Aqua;
}
.MaxHeightAndWidth
{
height:100%;
width:100%;
}
.NoBorder
{
border:0px;
}
ASP.NET
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewColoring.aspx.cs" Inherits="WebApplication1.GridViewColoring" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style/StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView id="testGrid" runat="server" CssClass="cssTable"
AutoGenerateColumns="False"
OnRowDataBound="SetStatusColors" >
<Columns>
<asp:TemplateField HeaderText="Description" SortExpression="description" ItemStyle-CssClass="NoMargin NoPadding">
<ItemTemplate>
<asp:Label ID="descriptionLbl" runat="server" Text='<%# Bind("description") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="Smaller" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Serial#" SortExpression="serial">
<ItemTemplate>
<asp:Label ID="serialNumberLbl" runat="server" Text='<%# Bind("serial") %>' CssClass="NoMargin NoPadding MaxHeightAndWidth NoBorder" Height="100%" Width="100%"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="Smaller" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
C# backend
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class GridViewColoring : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
testGrid.DataSource = MakeTable();
testGrid.DataBind();
}
protected void SetStatusColors(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < testGrid.Rows.Count; i++)
{
string serialNumber = ((Label)testGrid.Rows[i].FindControl("serialNumberLbl")).Text;
if (serialNumber != "0")
{
//GREEN HIGHLIGHTS
((Label)testGrid.Rows[i].FindControl("serialNumberLbl")).BackColor = System.Drawing.Color.FromArgb(204, 255, 204);
}
testGrid.Rows[i].BackColor = System.Drawing.Color.Yellow;
}
}
//mock db
private DataSet MakeTable()
{
var table = new DataTable("ParentTable");
DataColumn column;
DataRow row;
// Create new DataColumn, set DataType,
// ColumnName and add to DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "serial";
column.ReadOnly = true;
// Add the Column to the DataColumnCollection.
table.Columns.Add(column);
//// Create second column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "description";
column.AutoIncrement = false;
column.Caption = "Description";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the table.
table.Columns.Add(column);
// Instantiate the DataSet variable.
var dataSet = new DataSet();
// Add the new DataTable to the DataSet.
dataSet.Tables.Add(table);
// Create three new DataRow objects and add
// them to the DataTable
for (int i = 0; i <= 2; i++)
{
row = table.NewRow();
row["serial"] = i * 1000;
row["description"] = "Some desc " + DateTime.Now;
table.Rows.Add(row);
}
return dataSet;
}
}
}
Update
Changed the Serial# template's itemstyle and it fixed the problem. I have no idea why, but thanks to your tips, I was able to reduce the problem down enough to try it:
<ItemStyle Font-Size="Smaller" CssClass="NoMargin NoPadding" />
Try setting border-collapse: collapse; on the cssTable css class.
Okay I was able to get it working. I took the css classes off of the first template item and created the following css.
table.cssTable
{
border-collapse: collapse;
}
table.cssTable tr td
{
background: Yellow;
font-size:Smaller;
margin: 0;
padding: 0;
}
By the way, you should be able to get rid of the ItemStyle with font-size as well with this CSS.
I've created a fiddle but can't really see the problem I'm afraid - http://jsfiddle.net/5rBYb/1/
You might want to try adding this to your CSS though, which will set the borders to a single pixel (which I suspect is what's causing your problem).
table, th, td { border: 1px solid #000; }
Just change it to border: 0 if you want to hide borders.

Resources