Dynamically creating controls asp.net C# - c#

I have a website where you can take a multi-choice quiz. There can be 1 to 5 possible answers for each question in the quiz. I am having trouble figuring out how to dynamically making the controls for the quiz based on how many answers there are. I can get the number of answers easily.
so if there are 3 answers i need to generate 3 textboxes (readonly) and corresponding radiobutton list. Then when the user presses a button the data is submitted and the next question is loaded. I am trying to do this all in C#.

I once did exactly same but creating only textbox dynamically.I am copying my code(bit busy to make changes right now) ,please edit to your need:
<!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>
</head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
function GetDynamicTextBox(value)
{
return '<input name = "DynamicTextBox" class="dynamic" type="text" value = "' + "mymonthname" + '" />' +
'<input name = "DynamicTextBox1" class="dynamic" type="text" value = "' + "myYearname" + '" />' +
'<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox()
{
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div)
{
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
// function RecreateDynamicTextboxes() {
// var values = "vishal";
// if (values != null) {
// var html = "";
// for (var i = 0; i < values.length; i++) {
// html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
// }
// document.getElementById("TextBoxContainer").innerHTML = html;
// }
// }
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="TextBoxContainer" style="text-align: center;" class="step">
</div>
<div>
<div style="text-align: center;" id="setPrinteraxcis1">
<input id="btnAdd" type="button" value="Add" onclick="AddTextBox()" class="ANPClass" />
</div>
</div>
</form>
</body>
and to access the values,you need to write below code in .cs"
string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
if (textboxValues == null || textboxValues.Length == 0)
{
string empty = "true";
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
this.Values = serializer.Serialize(textboxValues);
foreach (string textboxValue in textboxValues)
{
MultipleId.Add(textboxValue);
}
}
where MultipleId is an arraylist:
public ArrayList MultipleId = new ArrayList();
P.S.
I read your requirement that you need on basis of some critteria,then you can use an counter in AddTextbox method and loop to create desired number of textbox.

Related

Print Preview of gridview is not center allign

I am trying to print one gridview . For that I gave a button and on button click I call javascript for printing tha grid.
function doPrint() {
var prtContent = document.getElementById('<%= grdHistoricalData.ClientID %>');
prtContent.border = 0; //set no border here
var WinPrint = window.open('', '', 'left=50,top=100,border=1px,width=1000,textAlign=center,height=1000,toolbar=0,scrollbars=1,status=0,resizable=1');
WinPrint.document.write(prtContent.outerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
This code is working fine but only thing is that print preview of gridview data is displaying left align.Normally Girdview Data is showing center align but when we print data shows in left align.
Gridview normal appearance
Print Preview of Gridview
Please help to do center align in print preview of Gridview.
There are several solutions I use in different circumstances.
1) external file. Load a small file to a iframe and call for data from parent.
<!--print.html -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Printer version</title>
<script type="text/javascript">
window.onload = function () {
var a = this.parent.getContent();
document.body.innerHTML = a;
}
function printMe() {
window.print();
}
</script>
<link href="/Styles/print.css" media="print" rel="stylesheet" />
</head>
<body>
</body>
</html>
Parent document.
<div id="divPrint" style="display:none;">
<div class="popup">
<div style="overflow:hidden;">Printer Version
<div style="float:right;">
<input type="button" ID="btnPrnClose" value="X" onclick="return closePrint()" />
</div>
</div>
<iframe id="frPrint" style="width:100%;"></iframe>
</div>
</div>
</div>
<script type="text/javascript">
function getContent() {
return '<div>' +
'<div class="right no-print" onclick="printMe();" style="cursor: pointer;" title="Print"> \
<img alt="Print" src="/images/printer.png" /></div>' + document.getElementById('gvOuterContainer').innerHTML+ '</div>';
}
function closePrint() {
document.getElementById('divPrint').style.display = 'none';
}
function PrintMessage() {
document.getElementById('divPrint').style.display = '';
document.getElementById('frPrint').src = "print.html?a=" + Math.random();//force no-cache
return false;
}
</script>
2) Print from the page.
<style type="text/css" media="print">
*
{
border: none!important;
}
.noprint,.popup
{
display: none!important;
}
#scrollContainer
{
width: auto!important;
}
.pop-show
{
display: table!important;
left: 0;
margin-left: 0;
top: 0;
width: 100%!important;
z-index: 100;
}
/* and so on */
</style>
Details may differ.
Finally got answer , I need to set gridview property that resolve this issue
<asp:TemplateField ItemStyle-HorizontalAlign="Center">

WebMatrix startersite progressbar while importing CSV

I'm newbie in building websites I'm using Razor C# in Webmatrix and I need help with progress bar while importing CSV files in my code. Below you can see my source.
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Import CSV";
}
#using System.Data;
#using System.Data.OleDb;
#using Microsoft.Web.Helpers;
#{
// Upload File
var fileName = "";
if ((IsPost) && (Request["Action"]!="Delete") && Request["Action"]!="Import" && (Request.Files[0].FileName!="")) {
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
}
// Import File
bool importSuccess = false;
if (IsPost && Request["Action"]=="Import"){
// Initialize connection variables
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" +
Server.MapPath("~/Uploads/") + #"; Extended Properties=""text;HDR=Yes;"";";
string CommandText = "select * from "+Request["filename"];
OleDbConnection myConnection = new OleDbConnection(ConnectionString);
OleDbCommand myCommand = new OleDbCommand(CommandText, myConnection);
DataSet dataset = new DataSet();
var insertCSV = "";
var rowNum = 0;
// Open connection
myConnection.Open();
// Fill DataSet
OleDbDataAdapter oda = new OleDbDataAdapter(myCommand);
oda.Fill(dataset);
// Close connection
myConnection.Close();
var db = Database.Open("StarterSite");
// Transactions
if(Request.Form["ImportType"]=="Transactions"){
string var0;
int var1;
string var2;
string var3;
string var4;
string var5;
string var6;
string var7;
string var8;
int var9;
DateTime var10;
decimal var11;
decimal var12;
string var13;
int count = dataset.Tables[0].Rows.Count;
while(rowNum <= dataset.Tables[0].Rows.Count-1){
var0=dataset.Tables[0].Rows[rowNum][0].ToString();
var1=Convert.ToInt32(dataset.Tables[0].Rows[rowNum][1].ToString());
var2=dataset.Tables[0].Rows[rowNum][2].ToString();
var3=dataset.Tables[0].Rows[rowNum][3].ToString();
var4=dataset.Tables[0].Rows[rowNum][4].ToString();
var5=dataset.Tables[0].Rows[rowNum][5].ToString();
var6=dataset.Tables[0].Rows[rowNum][6].ToString();
var7=dataset.Tables[0].Rows[rowNum][7].ToString();
var8=dataset.Tables[0].Rows[rowNum][8].ToString();
var9=Convert.ToInt32(dataset.Tables[0].Rows[rowNum][9].ToString());
var10=Convert.ToDateTime(dataset.Tables[0].Rows[rowNum][10].ToString());
var11=Convert.ToDecimal(dataset.Tables[0].Rows[rowNum][11].ToString());
var12=Convert.ToDecimal(dataset.Tables[0].Rows[rowNum][12].ToString());
var13=dataset.Tables[0].Rows[rowNum][13].ToString();
rowNum++;
insertCSV = "INSERT INTO Transactions (TransactionType, TransactionNumber, DeliveryAcc, AccountName, RepCode, CustCode, PartNo, Description, ProductGroup, Qty, TransactionDate, Sales, Cost, InvoiceAcc) VALUES(#0, #1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11, #12, #13)";
db.Execute(insertCSV, var0, var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12, var13);
}
importSuccess = true;
}
// Rep Codes
if(Request.Form["ImportType"]=="RepCodes"){
string var0;
string var1;
// Customer Types
}
if(Request.Form["ImportType"]=="CustTypes"){
}
}
// Delete File
bool deleteSuccess = false;
var fileNameDelete = "";
if (IsPost && (Request["Action"]=="Delete")) {
fileNameDelete = Request["filename"];
var fullPath = Server.MapPath("~/Uploads/" + fileNameDelete);
if (File.Exists(fullPath))
{
File.Delete(fullPath);
deleteSuccess = true;
}
}
}
<hgroup class="title">
<h1>#Page.Title.</h1>
<h2></h2>
</hgroup>
<div>
<h1>File Upload</h1>
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Upload"
)
#if (IsPost && Request["Action"]!="Delete" && Request["Action"]!="Import" && Request.Files[0].FileName!="") {<span>File uploaded!</span><br/>}
<h2>List of available files:</h2>
#if(deleteSuccess){
<h5>File #Request["filename"] deleted!!!</h5>
}
#if(importSuccess){
<h5>File #Request["filename"] imported!!!</h5>
}
<table>
<tr>
<th>File Name</th>
<th>Action</th>
</tr>
#foreach (string fullFilePath in Directory.GetFiles(Server.MapPath("~/Uploads"))){
<tr>
<td>#Path.GetFileName(fullFilePath);</td>
#if(Path.GetFileName(fullFilePath).Substring(Path.GetFileName(fullFilePath).Length-3)=="csv"){
<td style="width: fit-content;">
<form method="post">
<select name="ImportType" style="width: auto;">
<option value="Transactions" SELECTED>Transactions</option>
<option value="RepCodes">Rep Codes</option>
<option value="CustTypes">Customer Types</option>
</select>
<input type="hidden" name="filename" value="#Path.GetFileName(fullFilePath)" />
<input type="submit" name="Action" value="Import" />
<input type="submit" name="Action" value="Delete" />
</form>
</td>
}else{
<td>
<form method="post">
<input type="hidden" name="filename" value="#Path.GetFileName(fullFilePath)" />
<input type="submit" name="Action" value="Delete" />
</form>
</td>
}
</tr>
}
</table>
</div>
As you can see my code already imports data and 600,000 records can be imported in less than minute but I want to show progress bar so user can see that website is doing something.
Any suggestions?
Thanks,
Thomas
Here is a javascript JQuery loader, untested but should work.
<head runat="server">
<title></title>
<meta http-equiv="x-ua-compatible" content="IE=9" />
<link href="css/Style.css" rel="stylesheet" type="text/css" />
<link href="css/ui-lightness/jquery-ui-1.9.2.custom.css" rel="Stylesheet" type="text/css" />
<script src="Scripts/jquery-1.10.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
function StartLoader() {
$("<div id='TheLoader'></div>")
.html("LOADING...")
.dialog({
modal: true,
position: ['center', 'middle'],
width: 150,
height: 90,
title: 'Loading',
resizable: false,
closeOnEscape: false,
open: function (event, ui) {
$(".ui-dialog .ui-dialog-titlebar-close").hide();
}
});
}
function EndLoader() {
$("#TheLoader").remove();
}
</script>
</head>
The closeOnEscape and open part in the Dialog keeps the user from being able to close the dialog.
Now to start the loading screen, call the StartLoader(); function from client side, and to close the loader, call the EndLoader(); function which will remove the div completely.
Sources: Google, JQuery UI, StackOverflow
EDIT: I have added a fiddle for the loader, check it out here
That is great. Now I know how to show modal dialogues. I changed html attribute of TheLoader
$("<div id='TheLoader'></div>")
.html('Please Wait...<br/><br/><div id="progress-holder"><div id="progress"></div></div><br/><span id="message">...</span>')
Is it possible to update width of:
<div id="progress">
while importing?
I tried with
function updateValue(perc) {
$("#progress").style.width = perc + "%"; }
but it doesn't work.

Why the document.getElementById('textbox') is null in javascript after C# already assigned it?

I already created a textbox id called txt which it empty at the start. After I click button, the C# assigned information from user input to txt.Text and it did display the result in txt textbox then calling the javascript function and I use document.getElementById('txt'); to get value that is already displayed. However the javascript is showing that the txt is null even the information is already displayed on textbox. I tried with alert, it does trigger when calling that function. I don't understand why?
C# codes,
protected void ButtonRequest_Click(object sender, EventArgs e)
{
//more codes, I cut this short to main point
txt.Text = deviceName;
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "call", "<script>CreateIsm();</script>", false);
}
In asp.net and javascript,
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" CodeBehind="~/Default.aspx.cs" Inherits="_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 id="Head1" runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js" type="text/javascript"></script>
<script>
// global variables
id = 'AUTH';
notes = '';
ismClassId = '';
caseType = '';
l1 = '';
l2 = '';
l3 = '';
// Create ISM Ticket
CreateIsm = function (funct) {
// alert("hello");
var textBox = document.getElementById('txt');
var txt = "Please add the following DNS entries\n" + textBox;
ismClassId = 'ServerName';
caseType = 'Request';
l1 = 'Request';
l2 = 'Network';
l3 = 'Static IP Address';
notes = txt;
//notes = $('#txt').val();
$.support.cors = true;
$.ajax({
type: "POST",
url: "http://serversite/SubmissionPage.aspx",
data: {
'Form_ID': '08.01.7',
'ISM_Class_ID': ismClassId,
'Case_Type': caseType,
'Level_1': l1,
'Level_2': l2,
'Level_3': l3,
'Case_Notes': notes,
'Contact_ID': id
},
success: function (data) {
//console.log(data);
var str = data;
var ticket = $(str).find("#ticketIDOutput").val();
var hreff = "http://egsd.jvservices.com/Form/SRApproval/SRApproval.aspx?ticketID=" + ticket;
var a = "<a href='" + hreff + "' target='blank'>" + ticket + "</a> created."
$('#output').html(a);
},
error: function (jqXHR, textStatus, errorThrown) {
$('#output').html("Error creating ISM ticket: " + textStatus + " - " + errorThrown);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<center>
<asp:Button ID="ButtonRequest" runat="server" onclick="ButtonRequest_Click"
Text="Request" Visible="False" style="height: 26px" />
<br />
<br />
<div id="output">
</div>
<asp:TextBox ID="txt" runat="server" visible="true" TextMode="MultiLine"
Width=356px Height=200px style="margin-left: 0px"></asp:TextBox>
</center>
</form>
</body>
</html>
You need to access ClientID
var textBox = document.getElementById('<%=txt.ClientID %>');
If you are using .Net framework 4.0 or higher you can use ClientIDMode Enumeration on your control.
In your aspx page specify ClientIDMode = "Static" wiht your control like:
<asp:TextBox ID="txt" ClientIDMode="Static" runat="server" visible="true" TextMode="MultiLine"
Width=356px Height=200px style="margin-left: 0px"></asp:TextBox>
and then you can access it like:
var textBox = document.getElementById('txt');
If you look at the markup generated in your browser.. you'll see that the ID isn't actually what you think it is.
You can force it to be what you want.. by setting the ClientIDMode to Static:
<asp:TextBox ID="txt" runat="server" visible="true" TextMode="MultiLine"
Width=356px Height=200px style="margin-left: 0px" ClientIDMode="Static"></asp:TextBox>
Or you could use the ClientID property of the control in your page code.

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.

Categories

Resources