Importing data to google maps though Asp.net/C# - c#

I build an example and made it run, but the problem is, that it only shows one of the markers instead of them both.
This is what is in my repeater.
12.545020 55.675020 , 12.388520 55.618460
My code looks like this
<asp:Repeater ID="rptMarkers" runat="server">
<ItemTemplate>
<asp:Label ID="lbl_Adresse" CssClass="LongitudeLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Longitude")%>' />
<asp:Label ID="Label1" CssClass="LatitudeLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Latitude")%>' />
<asp:Label ID="Label2" CssClass="LocationLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Adresse")%>' />
<asp:Label ID="lbl_Fornavn" CssClass="Cust_NameLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Fornavn")%>' />
<asp:Label ID="lbl_Titel" CssClass="DescriptionLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Titel")%>' />
<asp:Label ID="Label3" CssClass="BilledeLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Billede")%>' />
<asp:Label ID="Label4" CssClass="IDLabel" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "BrugerID")%>' />
</ItemTemplate>
,
my javascript look like this
var markers = { locationLatitude: "", locationLongitude: "", Cust_Name: "", Description: "" };
var markerArray = [];
window.onload = function () {
var t = self.setTimeout(function () {
var size = $('.LocationLabel').length;
for (i = 0; i < size; i++) {
var id = $('.IDLabel').eq(i).text();
var Location = $('.LocationLabel').eq(i).text();
var CustName = $('.Cust_NameLabel').eq(i).text();
var Description = $('.DescriptionLabel').eq(i).text();
var Billede = $('.BilledeLabel').eq(i).text();
markers.locationLatitude = $('.LatitudeLabel').eq(i).text();
markers.locationLongitude = $('.LongitudeLabel').eq(i).text();
markers.Cust_Name = CustName;
markers.Description = "Navn: " + CustName + "<br />" + "Titel: " + Description + "<br />" + Billede + "<br />" + 'Se Profil';
markerArray.push(markers);
}
var mapOptions = {
center: new google.maps.LatLng(markers.locationLatitude, markers.locationLongitude),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
for (i = 0; i < markerArray.length; i++) {
var data = markerArray[i]
var myLatlng = new google.maps.LatLng(data.locationLatitude, data.locationLongitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.Cust_Name
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.Description);
infoWindow.open(map, marker);
});
})(marker, data);
}
});
}
This example works, but it dont show all the markers on the map

Related

c# jquery issues with limit characters

I've got a problem. I have a Gridview filled with a Datatable. When I display the result, I limit the number of characters (300) per rows. I put a button, when you click on it, it opens a pop-up and should display the whole result with no characters limitation. But the problem is that it doesn't display the whole result and I don't know how to do that, I tried to make an invisible datagridview to get its result but I think I'm doing it wrong 'cause it's like I didn't create it
Code html :
<Columns>
<asp:TemplateField HeaderText="Aggregation">
<ItemTemplate><%# Eval("Aggregation") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DerniereSolution">
<ItemTemplate><%# Eval("DerniereSolution") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DescriptionDemande">
<ItemTemplate><%# Eval("DescriptionDemande") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NomContact">
<ItemTemplate><%# Eval("NomContact") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Numero">
<ItemTemplate><%# Eval("Numero") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SousRubrique">
<ItemTemplate><%# Eval("SousRubrique") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TitreDemande">
<ItemTemplate><%# Eval("TitreDemande") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
Select
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Jquery :
jQuery.noConflict();
jQuery(document).ready(function($){
$(".select").click(function () {
ClearBackgroundColourOfRows();
var tr = $(this).parent().parent();
$(tr).css('background-color', '#A1DCF2');
<% %>
var children = $(tr).children();
var agg = $(children[0]).html();
var lastSol = $(children[1]).html();
var descr = $(children[2]).html();
var contact = $(children[3]).html();
var num = $(children[4]).html();
var rub = $(children[5]).html();
var title = $(children[6]).html();
var message = "<b>Titre Demande</b><br>" + title + "<br><br>" + "<b>Aggregation</b><br>" + agg + "<br><br>" + "<b>Dernière Solution</b><br>" + lastSol + "<br><br>" + "<b>Description Demande</b><br>" + descr + "<br><br>" + "<b>Nom Contact</b><br>" + contact + "<br><br>" + "<b>Numéro</b><br>" + num + "<br><br>" + "<b>Sous-Rubrique</b><br>" + rub;
$(".modal-body").empty();
$(".modal-body").html(message);
$('#myModal').modal('show');
});
function ClearBackgroundColourOfRows() {
$('#gvData tr').each(function () {
$(this).css('background-color', 'transparent');
});
}
$(".btn").click(function () {
ClearBackgroundColourOfRows();
});
});
Code c# :
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].Text = ((DataRowView)e.Row.DataItem).Row[2].ToString().Replace(tbSearch.Text, "<p>" + tbSearch.Text + "</p>");
e.Row.Cells[6].Text = ((DataRowView)e.Row.DataItem).Row[6].ToString().Replace(tbSearch.Text, "<p>" + tbSearch.Text + "</p>");//highlight words
e.Row.Cells[0].Text = ((DataRowView)e.Row.DataItem).Row[0].ToString().Substring(0, 300) + "...";//limit characters
e.Row.Cells[1].Text = ((DataRowView)e.Row.DataItem).Row[1].ToString().Substring(0, 300) + "...";
e.Row.Cells[2].Text = ((DataRowView)e.Row.DataItem).Row[2].ToString().Substring(0, 300) + "...";
}
Any ideas ?
Remove gvData_RowDataBound completely and use jQuery for limiting characters and displaying the full cell text in popup.Hope the example below helps you
Code behind:
public partial class CharacterLimitationExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
GetData();
}
private void GetData()
{
var d1 = new Data { Aggregation = "Row 1", DerniereSolution = "Row 1 really really long data", DescriptionDemande = "Row 1", NomContact = "Row 1", Numero = "Row 1", SousRubrique = "Row 1", TitreDemande = "Row 1" };
var d2 = new Data { Aggregation = "Row 2", DerniereSolution = "Row 2 really really long data", DescriptionDemande = "Row 2", NomContact = "Row 2", Numero = "Row 2", SousRubrique = "Row 2", TitreDemande = "Row 2" };
gvData.DataSource = new List<Data> { d1, d2 };
gvData.DataBind();
}
}
public class Data
{
public string Aggregation { get; set; }
public string DerniereSolution { get; set; }
public string DescriptionDemande { get; set; }
public string NomContact { get; set; }
public string Numero { get; set; }
public string SousRubrique { get; set; }
public string TitreDemande { get; set; }
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript">
$(function () {
var count = 0;
$('#gvData tr').each(function () {
debugger;
if (count != 0) {
var tr = $(this);
var children = $(tr).children();
var td1 = $(children)[0];
var span1 = $(td1).children()[0];
var data1 = $(span1).data('fulltext');
$(span1).text(data1.substring(0, 3) + "...");
var td2 = $(children)[1];
var span2 = $(td2).children()[0];
var data2 = $(span2).data('fulltext');
$(span2).text(data2.substring(0, 3) + "...");
var td3 = $(children)[2];
var span3 = $(td3).children()[0];
var data3 = $(span3).data('fulltext');
$(span3).text(data3.substring(0, 3) + "...");
}
count++;
});
$(".select").click(function () {
ClearBackgroundColourOfRows();
var tr = $(this).parent().parent();
$(tr).css('background-color', '#A1DCF2');
var children = $(tr).children();
var agg = $(children[0]).find('span').data('fulltext');
var lastSol = $(children[1]).find('span').data('fulltext')
var descr = $(children[2]).find('span').data('fulltext')
var contact = $(children[3]).html();
var num = $(children[4]).html();
var rub = $(children[5]).html();
var title = $(children[6]).html();
var message = "<b>Titre Demande</b><br>" + title + "<br><br>" + "<b>Aggregation</b><br>" + agg + "<br><br>" + "<b>Dernière Solution</b><br>" + lastSol + "<br><br>" + "<b>Description Demande</b><br>" + descr + "<br><br>" + "<b>Nom Contact</b><br>" + contact + "<br><br>" + "<b>Numéro</b><br>" + num + "<br><br>" + "<b>Sous-Rubrique</b><br>" + rub;
$(".modal-body").empty();
$(".modal-body").html(message);
$('#myModal').modal('show');
});
function ClearBackgroundColourOfRows() {
$('#gvData tr').each(function () {
$(this).css('background-color', 'transparent');
});
}
$(".btn").click(function () {
ClearBackgroundColourOfRows();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Aggregation">
<ItemTemplate>
<span data-fulltext='<%# Eval("Aggregation") %>'></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DerniereSolution">
<ItemTemplate>
<span data-fulltext='<%# Eval("DerniereSolution") %>'></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DescriptionDemande">
<ItemTemplate>
<span data-fulltext='<%# Eval("DescriptionDemande") %>'></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NomContact">
<ItemTemplate>
<%# Eval("NomContact") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Numero">
<ItemTemplate>
<%# Eval("Numero") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SousRubrique">
<ItemTemplate>
<%# Eval("SousRubrique") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TitreDemande">
<ItemTemplate>
<%# Eval("TitreDemande") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
Select
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
</body>
Output:

Button in asp.net web forms dont fire event

can you help me with something i struggle for 4 days, button event doesn't fire :( In the MasterPage i use this to add control
<Login:UserLogin runat="server" ID="UserLogin" EnableViewState="false" > </Login:UserLogin>
and the control is this
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserLogin.ascx.cs" Inherits="BookApartmentsPortal.controls.UserLogin" %>
<%# Register TagPrefix="MultiLanguage" Namespace="MultiLanguage.multilanguage" %>
<%--
<script type="text/javascript">
function DeleteKartItems() {
var inputEmail = $("#ctl00_UserLogin_txtEmailVal").val();
var user = {
email: "s.krastanov",
password: "1"
};
$.ajax({
type: "POST",
url: 'PublicDefault.aspx/Getvalues',
data: JSON.stringify({ person: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
$("#ctl00_PublicDefault_buttonLog").Click();
}
</script>--%>
<h3>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral13" runat="server" Resource="669" />
</h3>
<form action="/" method="POST" id="formasd">
<div class="">
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral14" runat="server" Resource="858" />
<%--user name input field--%>
<input type="text" class="modal-input" runat="server" size="20" id="txtEmailVal"
name="txtEmail" />
<%-- <asp:TextBox runat="server" CssClass="modal-input" ID="txtEmailVal" ></asp:TextBox> --%>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral21" runat="server" Resource="205" />
<%--password input field--%>
<%--<input type="password" class="modal-input" runat="server" size="1" maxlength="20" id="txtPassword" />--%>
<asp:TextBox runat="server" CssClass="modal-input" TextMode="Password" ID="txtPassword"
MaxLength="20" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server">
</asp:Label>
<asp:Panel ID="panelLogin" runat="server" DefaultButton="btnLogon">
<asp:Button runat="server" ID="btnLogon" Text="Click" CssClass="login-btn" OnClick="btnLogon_Click"></asp:Button>
</asp:Panel>
<%-- <button class="login-btn" runat="server" id="btnLogon" name="btnLogon" onclick="DeleteKartItems()">
<i class="fa fa-paper-plane"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
</button>--%>
<div id="divResult">
</div>
</div>
</form>
<asp:HyperLink ID="LoginFB" Target="_blank" runat="server" CssClass="btn btn-block btn-social btn-facebook fb-login">
<i class="fa fa-facebook"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral27" runat="server" Resource="1306" /></asp:HyperLink>
<a href="#lost-pass" class="button-modal various-login"><i class="fa fa-lock"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral22" runat="server" Resource="164" /></a>
<a href="#reg" class="button-modal reg"><i class="fa fa-user"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral23" runat="server" Resource="1271" /></a>
Backend is this:
public partial class UserLogin : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
Response.Write("you click");
}
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
LoginFB.NavigateUrl = "https://www.facebook.com/v2.0/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + ConfigurationManager.AppSettings["URL"].ToString() + "/Publish/UserFB.aspx&response_type=code&state=1";
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
//btnLogon.ServerClick += new EventHandler(btnLogon_Click);
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
//btnLogon.ServerClick += new CommandEventHandler(btnLogonClick);
// btnLogon.Command += btnLogon_Click;
}
public void btnLogon_Click(object sender, EventArgs e)
{
Label1.Text = "submit button is press";
// if (LoginSet == false )
// {
string Name = txtPassword.Text;
string Dev = txtEmailVal.Value;
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal.Value.Trim(), txtPassword.Text.Trim(), true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now;
FormsAuthentication.RedirectFromLoginPage(txtEmailVal.Value.Trim(), false);
Session["LoginUserName"] = txtEmailVal.Value.Trim();
// _loginSet = true;
}
else
{
// _loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
// _loginSet = false;
}
//}
}
}
This control is for login form and i just cant get the values from input boxes because event don't trigger. One idea was to make AJAX post to static method but after that i cant make new session with this variables.
I try everything and this button just doesn't fire the event. I don't know what to do next, can you help me.
Ok after one more day of struggle, i manage to make a little walk around path:
In the first step i made a Button to fire event (javascript function) and make cookie, after that i make click event for actual asp:Button :
<script type="text/javascript">
function LoginClicked() {
var inputEmail = $("#txtEmail").val();
var inputPass = $("#txtPassword").val();
if(inputEmail != "" && inputPass != ""){
var userSet = inputEmail + "&" + inputPass;
setCookie("UserSettings", userSet, 1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
$("#ctl00_UserLogin_btnLogon").click();
}
}
</script>
And here is the buttons:
<asp:Panel runat="server" ID="panekl">
<asp:Button runat="server" ID="btnLogon" UseSubmitBehavior="false" CssClass="no-display" ></asp:Button>
</asp:Panel>
<button class="login-btn" id="btnLogon1" name="btnLogon1" onclick="LoginClicked()">
<i class="fa fa-paper-plane"></i><MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
And in the back end, i get the cookie, split it, and check for validation:
public void btnLogon_Click()
{
if (LoginSet == false )
{
string[] txtSome = Request.Cookies["UserSettings"].Value.Split('&');
if (Request.Cookies["UserSettings"] != null && txtEmailVal != "" && txtPassword != "")
{
txtEmailVal = txtSome[0].Trim();
txtPassword = txtSome[1].Trim();
}
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal, txtPassword, true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Session["IdUserLogin"] = txtEmailVal;
_loginSet = true;
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Label1.Text = "submit button is press";
}
else
{
_loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
_loginSet = false;
}
}
}
This was the only way i figured out to get values from the control.

Dynamic grid on ASP.NET

I here to seek an advice ,what is the best approach.
here is the scenario.
I am building my project ASP.NET (C#)
I need to add an dynamic drop down box based on that two other text box related to drop down.
for example :
I have a button called "ADD LANDSCAPE", every time this triggered, i have to create an dynamic drop down "ddlLandscap" and two text boxes so the user can enter landscape value for each text box.
Can you guys please advise what's the best approach
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CS1.aspx.cs" Inherits="workout.CS1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="../jquery/jquery-ui.css" rel="stylesheet" />
<script src="../jquery/jquery-1.12.0.js"></script>
<script src="../jquery/jquery-ui.js"></script>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
.table {
border: 1px solid #ccc;
border-collapse: collapse;
}
.table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
.table th, .table td {
padding: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers1" CssClass="table" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Slno" ItemStyle-Width="50px" ItemStyle-CssClass="Slno">
<ItemTemplate>
<%# Eval("Slno") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
<ItemTemplate>
<%# Eval("Country")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Option">
<ItemTemplate>
<asp:Button ID="lnkDelete" runat="server" Text="Delete" OnClientClick="Confirmationbox(this);" />
<asp:Button ID="btn_update" runat="server" Text="Update" OnClientClick="updateable(this);" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnNewUser" runat="server" Text="Add" OnClientClick="return false;" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" OnClientClick="formatData()" />
<br />
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" Text="" />
</td>
<td style="width: 150px">Country:<br />
<asp:TextBox ID="txtCountry" runat="server" Width="140" Text="" />
</td>
</tr>
</table>
</div>
<div id="dialog-form-edit" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<asp:HiddenField ID="hdslno" runat="server" Value="" />
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">Name:<br />
<asp:TextBox ID="TextBox1" runat="server" Width="140" Text="" />
</td>
<td style="width: 150px">Country:<br />
<asp:TextBox ID="TextBox2" runat="server" Width="140" Text="" />
</td>
</tr>
</table>
</div>
<br />
<script type="text/javascript">
var dialog,editDialog;
function formatData() {
var formatdata = "";
$( '#gvCustomers1 tr:gt(0)' ).each( function () {
$( this ).find( 'td' ).each( function () {
if ( $( this ).hasClass( "Slno" ) || $( this ).hasClass( "Name" ) || $( this ).hasClass( "Country" ) ) {
formatdata += $( this ).html() + "|";
}
} );
formatdata += ",";
} );
alert( formatdata );
return false;
}
$(function () {
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": AddRow,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
$("#txtName").val("");
},
open: function () {
var nr = $('#dialog-form').data('param');
if (nr) {
$("#txtName").val(nr);
} else {
$("#txtName").val("");
}
}
});
editDialog = $("#dialog-form-edit").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": UpdateRow,
Cancel: function () {
editDialog.dialog("close");
}
},
close: function () {
$("#txtName").val("");
},
open: function () {
var nr = $('#dialog-form-edit').data('param');
console.log(nr);
$( "#hdslno" ).val( nr.slno );
$("#TextBox1").val(nr.name);
$("#TextBox2").val(nr.country);
}
});
});
$("#btnNewUser").button().on("click", function () {
dialog.dialog("open");
});
function Confirmationbox(obj) {
if (confirm("Do you want to delete this Customer?")) {
var row = $(obj).closest("tr");
row.remove();
}
return true;
}
function updateable(obj) {
var row = $(obj).closest("tr");
var slno = $(row).find("td").eq(0).html();
var name = $(row).find("td").eq(1).html();
var country = $(row).find("td").eq(2).html();
try {
var json = {
slno: slno,
name: name,
country: country
};
editDialog.data('param', json).dialog("open");
event.preventDefault();
} catch (e) {
alert(e);
}
return false;
}
function UpdateRow() {
var slno = $( "#hdslno" ).val();
var m_Name = $( "#TextBox1" ).val();
var m_Country = $( "#TextBox2" ).val();
var row = null;
$( '#gvCustomers1 tr:gt(0)' ).each( function () {
$( this ).find( 'td' ).each( function () {
if ( $( this ).hasClass( "Slno" ) && $( this ).html() == slno ) {
row = $( this ).closest( "tr" );
}
} )
} );
if ( row ) {
$( row ).find( "td" ).eq( 1 ).html( m_Name );
$( row ).find( "td" ).eq( 2 ).html( m_Country );
}
editDialog.dialog( "close" );
return false;
}
function AddRow() {
//Reference the GridView.
var gridView = document.getElementById("<%=gvCustomers1.ClientID %>");
//Reference the TBODY tag.
var tbody = gridView.getElementsByTagName("tbody")[0];
//Reference the first row.
var row = tbody.getElementsByTagName("tr")[1];
//Check if row is dummy, if yes then remove.
if (row.getElementsByTagName("td")[0].innerHTML.replace(/\s/g, '') == "") {
tbody.removeChild(row);
}
//Clone the reference first row.
row = row.cloneNode(true);
var legnth = gridView.rows.length;
SetValue1(row, 0, "Slno", legnth);
//Add the Name value to first cell.
var txtName = document.getElementById("<%=txtName.ClientID %>");
SetValue(row, 1, "name", txtName);
//Add the Country value to second cell.
var txtCountry = document.getElementById("<%=txtCountry.ClientID %>");
SetValue(row, 2, "country", txtCountry);
//Add the row to the GridView.
tbody.appendChild(row);
dialog.dialog("close");
return false;
}
function SetValue(row, index, name, textbox) {
row.cells[index].innerHTML = textbox.value;
textbox.value = "";
}
function SetValue1(row, index, name,leng) {
row.cells[index].innerHTML = leng;
}
</script>
<asp:HiddenField ID="hdTableValues" runat="server" Value="" />
</form>
</body>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace workout
{
public partial class CS1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
string query = "SELECT '' Slno, Name, Country FROM dd_Detils";
string constr = "Data Source=localhost;Initial Catalog=DataBase;User ID=sa;Password=globalfocus";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
}
if (dt.Rows.Count == 0)
{
//If no records then add a dummy row.
dt.Rows.Add();
}
gvCustomers1.DataSource = dt;
gvCustomers1.DataBind();
}
protected void Submit(object sender, EventArgs e)
{
int cnt = gvCustomers1.Rows.Count;
if (!string.IsNullOrEmpty(Request.Form["name"]) && !string.IsNullOrEmpty(Request.Form["country"]))
{
//Fetch the Hidden Field values from the Request.Form collection.
string[] names = Request.Form["name"].Split(',');
string[] countries = Request.Form["country"].Split(',');
//Loop through the values and insert into database table.
for (int i = 0; i < names.Length; i++)
{
string constr = "Data Source=localhost;Initial Catalog=Database;User ID=sa;Password=globalfocus";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dd_Detils VALUES(#Name, #Country)"))
{
cmd.Parameters.AddWithValue("#Name", names[i]);
cmd.Parameters.AddWithValue("#Country", countries[i]);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
//Refresh the page to load GridView with records from database table.
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}

load codebehind Gridview dynamically

I am generating this tags (IT,Marketing....) dynamically(codebehind) from the sql using linq to sql.
And when you click on any of the the tabs it will show the gridview as per table created in database.
But the gridview binding is done during page_load event, so everything is generated during page_load, now when you click any of the blue tabs , it will show you pre-generated gridviews.
Now i want to generate or load gridviews when i clck on [+] sign of any of the tabs and not during the page load
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div id="CONTAINER" onclick="">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="clickable mfiles" onclick="showHide('subm');changesign('signm');">
<span id="signm" class="plusMinus">[+]</span><span> M-Files<br />
</span>
</div>
<div id="subm">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
<script>
function showHide(id) {
__doPostBack('UpdatePanel1', id);
var el = document.getElementById(id);
//if (el && el.style.display == 'block') {
// el.style.display = 'none';
//}
//else {
// el.style.display = 'block';
//}
}
function changesign(id1) {
var xy = document.getElementById(id1);
if (xy.innerHTML == "[-]") {
xy.innerHTML = "[+]";
}
else {
xy.innerHTML = "[-]";
}
}
</script>
banckend code:
protected void Page_Load(object sender, EventArgs e)
{
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var depts = context.spi_GetNoOfDept();
PlaceHolder1.Controls.Clear();
int i = 1;
foreach (spi_GetNoOfDeptResult dept in depts)
{
Literal div = new Literal();
Contact deptinfo = new Contact();
deptinfo.NAME_LAST = dept.DEPT_NAME;
deptinfo.DEPT_ID = dept.DEPT_ID.ToString();
div.Text = "<div class=\"even clickable\" onclick=\"showHide('sub" + dept.DEPT_ID + "');changesign('sign" + dept.DEPT_ID + "');\">";
div.Text += "<span id=\"sign" + dept.DEPT_ID + "\">[+]</span><span>" + dept.DEPT_NAME + "</span>";
div.Text += "</div>";
div.Text += "<div id=\"sub" + dept.DEPT_ID + "\" style=\"margin-left:15px ;\">";
//GridView gd = CreateDynamicTable(dept.DEPT_ID);
i++;
PlaceHolder1.Controls.Add(div);
PlaceHolder1.Controls.Add(new LiteralControl("</div>"));
}
private GridView CreateDynamicTable(int x)
{
GridView gd = new GridView();
gd.ID = "grd" + x;
gd.AlternatingRowStyle.CssClass = "altrowstyle1";
gd.RowStyle.CssClass = "rowstyle1";
gd.HeaderStyle.CssClass = "grdhdr";
gd.GridLines = GridLines.None;
List<Contact> contacts = new List<Contact>();
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var persons = context.spi_GetContacts();
var items = context.spi_GetDept(x);
var depts = context.spi_GetNoOfDept();
foreach (spi_GetDeptResult item in items)
{
Contact contact = new Contact();
contact.NAME_LAST = item.NAME_LAST;
contact.NAME_FIRST = item.NAME_FIRST;
contact.PHONE_CELL = item.PHONE_CELL;
contact.ADDRESS = item.ADDRESS;
contact.APT = item.APT;
contact.DEPT_ID = item.DEPT_ID.ToString();
contact.DEPT_NAME = item.DEPT_NAME;
contacts.Add(contact);
//ddl_db.Items.Add(new ListItem(person.NAME_FIRST));
}
gd.CssClass = "gdmain";
gd.DataSource = contacts;
gd.DataBind();
return gd;
}
If you use a Multiview control for your tab container then you should be able to bind your code to load the Gridview to the ActiveViewChanged event and change your ActiveViewIndex property for that Multiview when your users navigate between your tabs.

Iterate through JSON Array and show result in a HTML table

I try to iterate through an array and show the results in a HTML table. The Data is coming from a webservice.
My JavaScript function:
function loadDate() {
var PanelID = document.getElementById('PanelID').value;
alert(PanelID);
$.ajax({
type: "POST",
url: "../../WebService/QRCode.asmx/getDatetime",
data: "{ 'PanelID': '" + PanelID + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: true,
success: function(data) {
var table = document.createElement('table');
var str = '<table>';
str += '<tr><th>Von</th><th>Bis</th><th>Thema</th></tr>';
for(var i = 0; i < data.d.length; i++) {
str += '<tr><td>' + data.d[i].Von + '</td><td>' + data.d[i].Bis + '</td><td>' + data.d[i].Thema + '</td></tr>';
}
str += '</table>';
return str;
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = loadDate(data);
},
error: function(x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
}
HTML Part
<body>
<h1>
Check-In und Check-Out von Besprechungen</h1>
<form id="form1" runat="server">
<div id = "DataTable"> </div>
<p>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
Raumname:
<br />
<asp:TextBox type="text" name="Panels" ID="PanelID" value="" runat="server"></asp:TextBox>
<br />
<br />
<asp:TextBox type="text" ID="Table" mode="multiline" runat="server" Coloumns="100" Rows="200"
Height="230px" Width="405px"></asp:TextBox>
<br />
<br />
<asp:Button ID="button" runat="server" Text="Check-In" Width="99px" OnClientClick="return loadDate();" />
<asp:Button ID="button1" runat="server" Text="Check_Out" Width="99px" />
</p>
</form>
</body>
The Problem is that something is not working in my code. If I do it with the above code I can't display the values.
I think it has something to do wit the for clause, because
f i change the FOR clause for example:
for(var i = 0; i < data.d.length; i++) {
var VonDatum = data.d[i].Von;
$("#Table").val(VonDatum);
}
so I can display the Von value in a textbox. But if I do it like that the FOR clause is displaying only one value, but there are more than 30 values in the array.
My JSON-Data looks like:
{"d":[{"Von":"18.05.2012 00:00:00","Bis":"18.06.2012 00:00:00","Thema":"Raum ist gesperrt","PanelIDs":"FAT-1"}]}
OLD
return str;
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = loadDate(data);
NEW
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = loadDate(data);
return str;
but your str not set in any element so you want to set element ?
like this way
var existingDiv = document.getElementById('DataTable');
existingDiv.innerHTML = str;
Why do you have
return str;
Where are you returning it to? Should your code be
existingDiv.innerHTML = loadDate(str);

Categories