Value from LINQ dataset (GetFiles) into ListView? - c#

I have the following simple page;
<%# Import namespace="System.IO" %>
<script runat="server">
int pageSize = 10;
int pageNum = 1;
protected override void OnInit(EventArgs e)
{
var currentPage = Directory.GetFiles(#"C:\mypath", "*.pdf").Skip((pageNum - 1) * pageSize).Take(pageSize).OrderBy(c => c).ToArray();
Listview1.DataSource = currentPage;
Listview1.DataBind();
base.OnInit(e);
}
</script>
<!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>Test project</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ListView ID="Listview1" runat="server">
<LayoutTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<td>Titel</td>
<td>Size</td>
</tr>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><a href=''><%#Eval("Name") %></a></td>
<td>0 kb</td>
</tr>
</ItemTemplate>
</asp:ListView>
</form>
</body>
</html>
How do i get Filename, size, path etc into my Listview. If i just had a simple for each directly on the GetFiles, i could do something like
FileInfo f = new FileInfo(pdfFile);
long pdfSize = f.Length;
Response.Write(Path.GetFileName(pdfFile) + " - " + pdfSize.ToString() + "<br/>");
But how do i achive this in my ListView?

You are selecting the paths to the files not the files itself. Hence you cannot get the FileInfo's properties what raises your exception "DataBinding: 'System.String' does not contain a property with the name 'Name'"
This should work:
var currentPage = Directory.GetFiles(#"C:\mypath", "*.pdf").Skip((pageNum - 1) * pageSize).Take(pageSize).OrderBy(c => c).ToArray();
.Skip((pageNum - 1) * pageSize)
.Take(pageSize)
.OrderBy(c => c)
.Select(path => new System.IO.FileInfo(path)).ToArray();

You may need to create a new listviewitem collection and add your values to the collection using a loop. Then add the listviewitems back to the listview.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.items.aspx

Related

Create tab dynamically after some div in first tabs

Create tab dynamically after showing 20 div in first tab.Actually I am generating a div dynamically,there may be 100 div generated dynamically.I want to show 20 div in one tab and if there are 100 div there it will automatically generate 5 tabs with 20 div in each tabs.
<div id="TabbedPanels1" class="TabbedPanels">
<ul class="TabbedPanelsTabGroup">
<li class="TabbedPanelsTab" tabindex="0">tab1</li>
<li class="TabbedPanelsTab" tabindex="0">tab2</li>
</ul>
<div class="TabbedPanelsContentGroup">
<div class="TabbedPanelsContent">
<div id="slider1" class="sliderwrapper">
<div class="contentdiv">
12345
</div>
<div class="contentdiv">
12345
</div>
</div>
<div id="paginate-slider1" class="pagination">
</div>
<div id="paginate1-slider1" class="pagination2">
</div>
</div>
</div>
</div>
Here I created a jsFiddle which generates the tabs dynamically based on the number of contentDivs: http://jsfiddle.net/Z6HN9/ , it may help you achieve your goal.
the HTML code:
<div id="tabs">
<ul id="tabLinks"></ul>
</div>
the JavaScript code:
$(function () {
var neededDivCount = 100; // number of contentDivs for test purposes
var divPerTab = 20; // number of contentDivs / tabs for test purposes
// create the conentDivs dynamically for test purposes
for (var i = 1; i <= neededDivCount; i++) {
$("body").append('<div class="contentDiv">div' + i + 'content</div>');
}
// create the tabs and tabLinks based on the number of contentDivs in the document
var neededTabCount = Math.floor(($(".contentDiv").length - 1) / divPerTab) + 1;
for (var i = 1; i <= neededTabCount; i++) {
$("#tabs").append('<div id="tab' + i + '"></div>');
$("#tabLinks").append('<li>tab' + i + '</li>');
}
// loop through the contentDivs and append them to the correct tab
$(".contentDiv").each(function (index) {
var appendToTabIndex = Math.floor(index / divPerTab) + 1;
$(this).appendTo($("#tab" + appendToTabIndex));
});
$("#tabs").tabs();
});
You can use 2 nested repeaters.. The child one is generated from datatable the returns your content records (content divs) and the parent one is dynamically generated from Anonymous types list.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="RP.aspx.cs" Inherits="RP" %>
<!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 id="Head1" runat="server">
<title>Untitled Page</title>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" language="javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
$( "#tabs" ).tabs();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="tabs">
<%-- Tabs Links --%>
<asp:Repeater ID="TablLinkRepeater" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li><a href="#Tab<%# Eval("TabIndex") %>">Tab
<%# Eval("TabIndex") %></a></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
<%-- Tabs and Content --%>
<asp:Repeater ID="TabRepeater" runat="server">
<ItemTemplate>
<div id="Tab<%# Eval("TabIndex") %>">
<%-- Show TabIndex just for testing --%>
<h1>
Tab #
<%# Eval("TabIndex") %>
</h1>
<asp:Repeater ID="ContentRepeater" runat="server">
<ItemTemplate>
<div class="Content" id="ContentDiv" runat="server">
<%-- Some content--%>
<asp:Label ID="Name" runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public partial class RP : System.Web.UI.Page
{
private const int ContentPerTab = 20;
private DataTable SomeDatatable;
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//1) Load SomeDatatable from Database somehow
// Just for testing : replace with query to DB
SomeDatatable = new DataTable("x");
SomeDatatable.Columns.Add(new DataColumn("ContentIndex", Type.GetType("System.Int32")));
SomeDatatable.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
for (int x = 1; x <= 50; x++)
{
SomeDatatable.Rows.Add(new object[] {
x,
"Content " + x
});
}
///////////////////
//2) Create a dummy data source for the tab repeater using a list of anonymous types
List<object> TabList = new List<object>();
for (int I = 0; I < Math.Ceiling((decimal)SomeDatatable.Rows.Count / (decimal)ContentPerTab); I++)
{
TabList.Add(new { TabIndex = I });
}
TabRepeater.ItemDataBound += TabRepeater_ItemDataBound;
TabRepeater.DataSource = TabList;
TabRepeater.DataBind();
TablLinkRepeater.DataSource = TabList;
TablLinkRepeater.DataBind();
}
}
protected void TabRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
int TabIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "TabIndex").ToString(), out TabIndex);
//Copy Content Rows from SomeDatable that belong to this tab
DataTable Dt = SomeDatatable.Clone();
for (Int32 i = TabIndex * ContentPerTab; i <= (TabIndex + 1) * ContentPerTab - 1; i++)
{
if (i >= SomeDatatable.Rows.Count) break;
Dt.ImportRow(SomeDatatable.Rows[i]);
}
// Find the content repeater in this item and use the new datatable as source
Repeater ContentRepeater = (Repeater)e.Item.FindControl("ContentRepeater");
ContentRepeater.ItemDataBound += ContentRepeater_ItemDataBound;
ContentRepeater.DataSource = Dt;
ContentRepeater.DataBind();
}
}
//This handler might be needed for content repeater, included just for testing
protected void ContentRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
//Read coulmn from Datarow
int ContentIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "ContentIndex").ToString(), out ContentIndex);
// Find some label
Label Name = (Label)e.Item.FindControl("Name");
Name.Text = "Content #" + ContentIndex;
}
}
}

Google Maps Api does not display image

I have problem in implementing google maps api in asp.net. Here is my aspx code:
<%# Page Title="" Language="C#" AutoEventWireup="true" CodeFile="visual_loc.aspx.cs" Inherits="visual_loc" %>
<%--A sample project by Ghaffar khan--%>
<!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 id="Head1" runat="server">
<title>Your Data on Google Map </title>
<%--Google API reference--%>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false
&key=asdfg" type="text/javascript">
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<form id="form1" runat="server">
<asp:Panel ID="Panel1" runat="server">
<%--Place holder to fill with javascript by server side code--%>
<asp:Literal ID="js" runat="server"></asp:Literal>
<%--Place for google to show your MAP--%>
<div ID="map_canvas" style="width: 100%; height: 728px; margin-bottom: 2px;">
</div>
<br />
</asp:Panel>
<br />
</form>
</body>
</html>
And my code behind: getLocation() is the method which gets the longitude and latitude from my database. createDataTable() is method which create DataTable from those locations.
protected void Page_Load(object sender, EventArgs e)
{
string user_id;
user_id = Request.Cookies["cookie"]["Login"];
getLocation(user_id);
BuildScript( createDataTable());
}
private void BuildScript(DataTable tbl)
{
String Locations = "";
foreach (DataRow r in tbl.Rows)
{
// bypass empty rows
if (r["Latitude"].ToString().Trim().Length == 0)
continue;
string Latitude = r["Latitude"].ToString();
string Longitude = r["Longitude"].ToString();
// create a line of JavaScript for marker on map for this record
Locations += Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + Latitude + "," + Longitude + ")));";
}
// construct the final script
js.Text = #"<script type='text/javascript'>
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById('map_canvas'));
map.setCenter(new GLatLng(52.259, 21.012), 2);
" + Locations + #"
map.setUIToDefault();
}
}
</script> ";
}
whole operation result in displaying empty site with no content. What am i doing wrong?
Problem was that i did wrong directories to my markers, so that cannot be seen on Map. Once i did enter valid directories everything works.

add row from asp.net code behind to htmltable

I am trying to add a new row to HtmlTable on click of button Add Row.
It adds one row. But it doesn't add further rows. Please advise.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="eLaundrySearchWeb.Test" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="myTable" runat="server">
<tr>
<td>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</td>
<td>
<asp:TextBox ID="txtQty" runat="server">
</asp:TextBox>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Add Row" OnClick="AddRow_Click"
/>
</td>
</tr>
</table>
</div>
</form>
protected void AddRow_Click(object sender, EventArgs e)
{
//Random r=new Random();
//int rv=r.Next(0,100);
int numOfRows = myTable.Rows.Count;
HtmlTableRow row = new HtmlTableRow();
row.ID = "tbl_row"+(numOfRows+1);
HtmlTableCell cell1 = new HtmlTableCell();
cell1.ID = "tbl_cell1"+ (numOfRows+1);
TableCell cell2 = new TableCell();
cell2.ID = "tbl_cell2" + (numOfRows + 1);
TextBox tb = new TextBox();
tb.ID = "tbQty" + (numOfRows + 1);
cell1.Controls.Add(tb);
row.Cells.Add(cell1);
myTable.Rows.Add(row);
myTable.DataBind();
}
It is adding the rows every time you click the button.The only problem here is that the button is causing the postback and on postback the controls that were dynamically created are getting cleared.Then your button click event adds a row again.So it seems to you that the row is only added once.But in reality it is getting added everytime,it's just that on postback the earlier ones are getting cleared.
Trying converting your code into a function and call that function on postback.
Similar SO Question

How can I make JavaScript run in WebBrowser control?

In my winforms aplication I have a WebBrowser control named webBrowser1.
In code all I added is navigating to a page:
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://localhost:6489/Default.aspx");
}
The code for the page to which I navigate is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TableRowShow.Default" %>
<!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>
<script type="text/javascript">
window.onload = function()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
function attach()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
var i = 1; // position of next tr to be shown
function addDest()
{
var trs = document.getElementById('travelTable').getElementsByTagName('tr');
if (trs[i] != null)
trs[i++].style.display = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="travelTable">
<tr>
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
</table>
<asp:HyperLink runat="server" ID="addDestination"
ClientIDMode="Static" NavigateUrl="javascript:;" >
Add Destination
</asp:HyperLink>
</form>
</body>
</html>
Seen in a browser like IE or Chrome the page looks like this:
Clicking on Add Destination anchor creates a new input:
The problem that I'm having with WebBrowser control is that it loads the page but the JavaScript doesn't work.
If I click on Add Destination nothing happens, even though the same page works well in Chrome or IE.
Placing a breakpoint and using:
webBrowser1.Document.InvokeScript("addDestination");
inside the Immediate window and then continuing to run the program activates the JavaScript in that function adding a new input.
Thanks for replies!
Try attaching the click handlers like this instead of using setAttribute in the onload and attach functions:
document.getElementById('addDestination').onclick = addDest;
You could try setting the ScriptErrorsSuppressed property to false to see whether any JavaScript errors occur.

accessing Hyperlink Server Control within Repeater HeaderTemplate

How to access the 'HyperlinkID1' control with the headertemplate?
I like to change the value like below but i can't access the control because it keep telling that "The name 'HyperlinkID1' does not exist in the current context"
if (!IsPostBack)
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
else
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
<%# Page Language="C#" %>
<!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>
</head>
<script language="C#" runat="server">
public class PositionData
{
private string name;
private string ticker;
public PositionData(string name, string ticker)
{
this.name = name;
this.ticker = ticker;
}
public string Name
{
get
{
return name;
}
}
public string Ticker
{
get
{
return ticker;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
else
{
HyperlinkID1.ImageUrl = "asc.jpg";//change image
}
if (!IsPostBack)
{
ArrayList values = new ArrayList();
values.Add(new PositionData("Microsoft", "Msft"));
values.Add(new PositionData("Intel", "Intc"));
values.Add(new PositionData("Dell", "Dell"));
Repeater1.DataSource = values;
Repeater1.DataBind();
}
}
</script>
<body>
<form runat="server">
<b>Repeater1:</b>
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1">
<tr>
<td><b>Company</b>
<asp:HyperLink ID="HyperlinkID1" runat="server" ImageUrl="desc.jpg" NavigateUrl="nextpage.aspx">HyperLink</asp:HyperLink></td>
<td><b>Symbol</b></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "Name") %> </td>
<td><%# DataBinder.Eval(Container.DataItem, "Ticker") %> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
The control does not exist. You need to declare an OnItemCreated method linked to your repeater, and in this do a FindControl for the control name, and set the value in this.
ETA - in response to the comment.
<asp:Repeater OnItemCreated="rptItemCreated" >
.
.
.
And in the code you need to define the new method defined:
protected void rptItemCreated(Object Sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType==ListItemType.Header)
{
HtmlAnchor HyperLinkID1=(HtmlAnchor)e.Item.FindControl("HyperLinkID1");
HyperlinkID1.ImageUrl = IsPostBack?"asc.jpg":"asc.jpg;
}
}
Note this is typed from memory, and so may need some tweaking. Also I have put the code you had into an abreviated form, which is equivalent but briefer to format.

Categories

Resources