c# jquery issues with limit characters - c#

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:

Related

Importing data to google maps though Asp.net/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

DataTable in ViewState is Returning Deleted Rows

I am currently working on a dynamic gridview that will allow a user to add or delete rows in order to be saved as database entries later on.
My gridview markup is as such:
<asp:UpdatePanel ID="upAirporterSchedule" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvAirporterSchedule" runat="server" ShowFooter="true" AutoGenerateColumns="false" CssClass="table table-striped table-bordered table-hover dataTable no-footer" OnRowDataBound="gvAirporterSchedule_RowDataBound" OnRowCommand="gvAirporterSchedule_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Location" ItemStyle-Width="25%">
<ItemTemplate>
<asp:DropDownList ID="ddlScheduleLoc" runat="server" CssClass="form-control"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Start Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterStartDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("StartDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterEndDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("EndDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Departure Time">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterDepTime" runat="server" CssClass="form-control time-picker" Text='<%# Eval("DeptTimeColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-clock-o"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:TextBox ID="tbxAirporterDuration" runat="server" CssClass="form-control" Text='<%# Eval("DurationColumn") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="btnDel" runat="server" CssClass="btn btn-default" Text="Delete" CommandName="DeleteRow" />
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-default" Text="Add Entry" CommandName="AddRow" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Aside from this grid, I have some other fields in the user control. When I go to save, the user will click a button at the bottom of the user control which will package up the form fields above it and the grid into some classes and shoot this off to the database code to add/update this data.
Page.Validate("AirporterFares");
if (Page.IsValid)
{
try
{
// Save trip information.
SysVarService.SharedRideTrip trip = new SysVarService.SharedRideTrip();
if (_tripID > 0)
trip = Global.sysVarService.GetSharedRideTripByID(_tripID);
trip.isVisible = 1;
trip.productType = ReservationService.ProductType.TOUR;
trip.originStopID = Convert.ToInt32(ddlOrigin.SelectedValue.ToString());
trip.destinationStopID = Convert.ToInt32(ddlDestination.SelectedValue.ToString());
trip.defaultDuration = 0;
trip.effectiveDate = DateTime.Parse(tbxAirporterEffDate.Text.Trim());
trip.startTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
trip.endTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
// Save the two fare information.
SysVarService.SharedRideTrip_ShuttleFare aFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 1,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterAdultFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
SysVarService.SharedRideTrip_ShuttleFare cFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 2,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterChildFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
string status = "";
if (_updating)
status = Global.sysVarService.UpdateAirporterFare(trip, aFare, cFare, GetScheduleEntries());
else
status = Global.sysVarService.AddAirporterFare(trip, aFare, cFare, GetScheduleEntries());
if (!String.IsNullOrEmpty(status))
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = status;
return;
}
}
catch (Exception ex)
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = ex.ToString();
return;
}
Response.Redirect("~/Internal/Admin/Default.aspx?action=Airporter_Fares");
}
When I go to either add or update, I call GetScheduledEntries, which is supposed to loop through the datatable (grabbing it from the viewstate) and convert the templated fields into object properties and stuff these objects in a list.
private List<AdminConfigService.SharedRideTimes> GetScheduleEntries()
{
int idx = 0;
List<AdminConfigService.SharedRideTimes> schedule = new List<AdminConfigService.SharedRideTimes>();
if (gvAirporterSchedule.Rows.Count >= 1)
{
for (int i = 1; i <= gvAirporterSchedule.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
schedule.Add(new AdminConfigService.SharedRideTimes()
{
StartDate = DateTime.Parse(startDate.Text.Trim()),
EndDate = DateTime.Parse(endDate.Text.Trim()),
DepartureTime = DateTime.Parse(deptTime.Text.Trim()),
Duration = Convert.ToInt32(duration.Text.Trim()),
EffectiveDates = "",
StopID = Convert.ToInt32(ddl.SelectedValue.ToString())
});
idx++;
}
return schedule;
}
else
return schedule;
}
The problem is, if I delete rows from this grid view and then attempt to save the form, the datatable from the viewstate is bringing back those deleted rows and acting like they are still existing for saving, even though the gridview and the datatable do not have that row anymore (when the DeleteRow command goes through).
else if (e.CommandName == "DeleteRow")
{
SetRowData();
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int idx = gvr.RowIndex;
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[idx]);
currentRow = dt.NewRow();
ViewState["AirporterScheduleTable"] = dt;
gvAirporterSchedule.DataSource = dt;
gvAirporterSchedule.DataBind();
SetPreviousData();
}
}
}
private void SetPreviousData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
ddl.SelectedValue = dt.Rows[i]["LocColumn"].ToString();
startDate.Text = dt.Rows[i]["StartDateColumn"].ToString();
endDate.Text = dt.Rows[i]["EndDateColumn"].ToString();
deptTime.Text = dt.Rows[i]["DeptTimeColumn"].ToString();
duration.Text = dt.Rows[i]["DurationColumn"].ToString();
idx++;
}
}
}
}
private void SetRowData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable current = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
if (current.Rows.Count > 0)
{
for (int i = 1; i <= current.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
currentRow = current.NewRow();
current.Rows[i - 1]["LocColumn"] = ddl.SelectedValue;
current.Rows[i - 1]["StartDateColumn"] = startDate.Text;
current.Rows[i - 1]["EndDateColumn"] = endDate.Text;
current.Rows[i - 1]["DeptTimeColumn"] = deptTime.Text;
current.Rows[i - 1]["DurationColumn"] = duration.Text;
idx++;
}
ViewState["AirporterScheduleTable"] = current;
}
}
}
There doesn't seem to be any where in the code that I am not updating the ViewState datatable when I either delete or add entries to this dynamic gridview. What could be causing the difference in ViewStates? Does the full postback of the button outside of the UpdatePanel and GridView have a different ViewState?
I also pretty much followed this tutorial exactly.
Turned out to be one of those cases where you overlook something simple. When I was populating the grid with data on load, I did not protect it with a
if (!Page.IsPostback)
Because of that, every time the row was deleted, it would refill the data table with the data on Page Load and cause the weird issues where deleted rows didn't seem to be getting deleted.

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.

Insert <p> tags with C#?

This is sort of a weird question, but is there a way to insert <p> tags around some imported text? I have a list of blog entries, each of which comes from its own source (I think it's a copy-paste job into Sitecore). All entries have an "Introduction" which is the blurb about the article. Some of these has <p> tags enclosing them and others do not (I'm not sure why and I can't change the source material--I can only have control on how it looks when it comes into the blog listing page) I'm thinking there should be a check to see if they do exist first, although I am not sure how that could be done.
This is the front end for the blog listing:
<asp:GridView ID="EntryList" runat="server" OnItemDataBound="EntryDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" pagerstyle-cssclass="pagination" rowstyle-cssclass="norm" alternatingrowstyle-cssclass="altColor" width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<li class="wb-entry-list-entry" >
<div class="imgOuter">
<div class="imgInner">
<asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
</div>
</div>
<div class="outer">
<div class="wb-entry-detail" >
<h2>
<%# Eval("Title") %>
</h2>
<div class="wb-details">
<%# Eval("EntryDate") %>
<%# Eval("Author") %><br />
<%# Eval("AuthorTitle") %>
</div>
<%# Eval("Introduction") %>
<asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
<asp:PlaceHolder ID="CommentArea" runat="server">
<span class="wb-comment-count">
</span>
</asp:PlaceHolder>
</div>
</div>
</li>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
</EmptyDataTemplate>
And this is the codebehind:
Database db = Sitecore.Context.Database;
protected const string DEFAULT_POST_TEMPLATE = "/layouts/WeBlog/PostListEntry.ascx";
protected Size m_imageMaxSize = Size.Empty;
protected void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
EntryList.PageIndex = e.NewPageIndex;
string tag = Request.QueryString["tag"];
BindEntries(tag);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string requestedToShowStr = Request.QueryString["count"] ?? "0";
int requestedToShow = 0;
int.TryParse(requestedToShowStr, out requestedToShow);
string startIndexStr = Request.QueryString["startIndex"] ?? "0";
int startIndex = 0;
int.TryParse(startIndexStr, out startIndex);
string tag = Request.QueryString["tag"];
Item CurrentItem = Sitecore.Context.Item;
BindEntries(tag);
string blogUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);
}
}
protected void BindEntries(string tag)
{
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("EntryTable");
ResultTable.Columns.Add("EntryID", Type.GetType("System.String"));
ResultTable.Columns.Add("EntryPath", Type.GetType("System.String"));
ResultTable.Columns.Add("Title", Type.GetType("System.String"));
ResultTable.Columns.Add("EntryDate", Type.GetType("System.String"));
ResultTable.Columns.Add("Author", Type.GetType("System.String"));
ResultTable.Columns.Add("AuthorTitle", Type.GetType("System.String"));
ResultTable.Columns.Add("Introduction", Type.GetType("System.String"));
ResultTable.Columns.Add("Image", Type.GetType("System.String"));
Item CurrentItem = Sitecore.Context.Item;
Item BlogStart = ScHelper.FindAncestor(CurrentItem, "BlogHome");
Item[] EntryArray = null;
if (tag == "")
EntryArray = BlogStart.Axes.SelectItems(#"child::*[##templatename='Folder']/*[##templatename='Folder']/*[(##templatename='BlogEntry' ) ]");
else
EntryArray = BlogStart.Axes.SelectItems(#"child::*[##templatename='Folder']/*[##templatename='Folder']/*[(##templatename='BlogEntry' and contains(#tags,'" + tag + "' )) ]");
ArrayList PostList = new ArrayList();
if (EntryArray != null)
{
foreach (Item EntryItem in EntryArray)
{
if (EntryItem.Fields["Post Date"].Value != "")
{
BlogEntryProcessor.BlogEntrys obj1 = new BlogEntryProcessor.BlogEntrys();
obj1.Description = EntryItem.Fields["Introduction"].Value;
obj1.Guid = EntryItem.ID.ToString();
obj1.Link = ScHelper.GetPath(EntryItem);
obj1.PostDate = formatDateCmp(EntryItem.Fields["Post Date"].Value);
obj1.Title = EntryItem.Fields["Title"].Value;
PostList.Add(obj1);
}
}
PostList.Sort();
PostList.Reverse();
foreach (BlogEntryProcessor.BlogEntrys obj in PostList)
{
DataRow dr = ResultTable.NewRow();
Item BlogEntry = db.Items[obj.Guid];
dr["EntryID"] = obj.Guid;
dr["EntryPath"] = ScHelper.GetPath(BlogEntry);
dr["Title"] = BlogEntry.Fields["Title"].Value;
dr["EntryDate"] = GetPublishDate(BlogEntry);
dr["Author"] = GetAuthor(BlogEntry);
dr["AuthorTitle"] = GetAuthorTitle(BlogEntry);
dr["Introduction"] = BlogEntry.Fields["Introduction"].Value;
//TODO: get Default Image
string EntryThumbImage = BlogEntry.Fields["Thumbnail Image"].Value;
string EntryImage = BlogEntry.Fields["Image"].Value;
string ArtImage = "http://fpoimg.com/140x140";
if (EntryImage != "")
{
Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Image"];
ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
}
else if (EntryThumbImage != "")
{
Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Thumbnail Image"];
ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
}
dr["Image"] = ArtImage;
ResultTable.Rows.Add(dr);
}
EntryList.DataSource = ds;
EntryList.DataMember = "EntryTable";
EntryList.DataBind();
}
}
protected string GetAuthorTitle(Item entry)
{
string OutName = "";
string AuthorID = entry.Fields["Author"].Value;
Item AuthorItem = db.Items[AuthorID];
if (AuthorItem != null)
OutName = AuthorItem.Fields["Author Title"].Value;
return OutName;
}
protected string GetAuthor(Item entry)
{
string OutName = "";
string AuthorID = entry.Fields["Author"].Value;
Item AuthorItem = db.Items[AuthorID];
if (AuthorItem != null)
OutName = string.Format("<br />By <a href='{0}'>{1}</a>", ScHelper.GetPath(AuthorItem), AuthorItem.Fields["Author Name"].Value);
return OutName;
}
protected string GetPublishDate(EntryItem CurrentEntry)
{
string pDate = GOJOHelper.FormatDate(((Item)CurrentEntry).Fields["Post Date"].Value);
return pDate;
}
protected void EntryDataBound(object sender, ListViewItemEventArgs args)
{
if (args.Item.ItemType == ListViewItemType.DataItem)
{
var dataItem = args.Item as ListViewDataItem;
var control = dataItem.FindControl("EntryImage");
if (control != null)
{
var imageControl = control as global::Sitecore.Web.UI.WebControls.Image;
imageControl.MaxWidth = m_imageMaxSize.Width;
imageControl.MaxHeight = m_imageMaxSize.Height;
var entry = dataItem.DataItem as EntryItem;
if (entry.ThumbnailImage.MediaItem == null)
imageControl.Field = "Image";
}
}
}
//string to use to sort the dates - must have 2 digit for month and day
private string formatDateCmp(string date)
{
// Set the dateResult for the TryParse
DateTime dateResult = new DateTime();
// Split the date up. ie. 20090101T000000
string[] TempStr = date.Split('T');
// Set the date to the characters before the T
date = TempStr[0];
// Insert a slash after the first 4 characters and after 7
date = date.Insert(4, "/").Insert(7, "/");
return date;
}
You can always do something like...
dr["Introduction"] = BlogEntry.Fields["Introduction"].Value
.Replace("\n\n", "</p><p>");
... or whichever escape characters are being used to denote separation of paragraphs in your source data. Alternatively, you could use Regex utilities. See Example 3 in this article for further reference.
Firstly in your GridView you've got
OnItemDataBound="EntryDataBound"
OnItemDataBound isn't an event of GridView I'm a little surprised that works!
Use
OnRowDataBound="EntryList_RowDataBound"
This is my common pattern for GridView's and Repeaters, noticed I've used a Literal control in the HTML, I'm not a mega fan of Eval! Also note that if (dataItem == null) just if there's a data item for that row, RowTypes like header and footer don't have any data, it's easier than the typical if(e.Row.RowType == DataControlRowType.Header) etc
<asp:GridView ID="EntryList" runat="server" OnRowDataBound="EntryList_RowDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" PagerStyle-CssClass="pagination" RowStyle-CssClass="norm" AlternatingRowStyle-CssClass="altColor" Width="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<li class="wb-entry-list-entry">
<div class="imgOuter">
<div class="imgInner">
<asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
</div>
</div>
<div class="outer">
<div class="wb-entry-detail">
<h2>
<%# Eval("Title") %>
</h2>
<div class="wb-details">
<%# Eval("EntryDate") %>
<%# Eval("Author") %><br />
<%# Eval("AuthorTitle") %>
</div>
<asp:Literal runat="server" ID="IntroductionLiteral"/>
<asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
<asp:PlaceHolder ID="CommentArea" runat="server">
<span class="wb-comment-count"></span>
</asp:PlaceHolder>
</div>
</div>
</li>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
</EmptyDataTemplate>
</asp:GridView>
.cs file
protected void EntryList_RowDataBound(object sender, GridViewRowEventArgs e)
{
var dataItem = e.Row.DataItem as EntryItem;
if (dataItem == null)
return;
var imageControl = e.Row.FindControl("EntryImage") as global::Sitecore.Web.UI.WebControls.Image;
var introductionControl = e.Row.FindControl("IntroductionLiteral") as Literal;
if (imageControl == null || introduction == null)
return;
imageControl.MaxWidth = m_imageMaxSize.Width;
imageControl.MaxHeight = m_imageMaxSize.Height;
if (dataItem.ThumbnailImage.MediaItem == null)
imageControl.Field = "Image";
if (!string.IsNullOrEmpty(data["introduction"]))
introductionControl.Text = string.Format("<p>{0}</p>", data["introduction"].ToString().Replace("\n\r", "</p><p>"));
}
Also if you've got a list of Sitecore objects why don't you just bind that to the GridView, then in your RowDataBound method get the item back
var dataItem = e.Row.DataItem as Item;
and then do the logic in the BindEntries method in there, would prob be cleaner code and you wouldn't have to use stupid DataSets! Just an idea.

How to transfer item from one datalist to other datalist?

I have a datalist
<asp:DataList ID="dlstImage" runat="server" RepeatDirection="Horizontal" RepeatColumns="5"
CellSpacing="8">
<ItemTemplate>
<asp:ImageButton ID="Image" runat="server" ImageUrl='<%#"~/Controls/ShowImage.ashx?FileName=" +DataBinder.Eval(Container.DataItem, "FilePath") %>'
OnCommand="Select_Command" CommandArgument='<%# Eval("Id").ToString() +";"+Eval("FilePath")+";"+Eval("Index") %>' /><br />
<asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%>
</ItemTemplate>
</asp:DataList>
In which i am binding the image after uploading through uplodify upload, now i have one more datalist
and two btn up and down,
<asp:ImageButton ID="ibtnMoveUp" runat="server" ImageUrl="~/App_Themes/Default/Images/moveup.bmp"
Style="height: 16px" ToolTip="MoveUp The Item" />
<asp:ImageButton ID="ibtnMoveDown" runat="server" ImageUrl="~/App_Themes/Default/Images/movedown.bmp"
ToolTip="MoveDown The Item" />
<asp:DataList ID="dlstSelectedImages" runat="server" RepeatDirection="Horizontal"
RepeatColumns="5" CellSpacing="8">
<ItemTemplate>
<asp:ImageButton ID="Image" runat="server" /><br />
<asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%>
</ItemTemplate>
</asp:DataList>
My both datalist is in the same webuser control, datalist1 and datalist2 and I have 2 btn up and down, when i select one image from datalist1 and click on down btn then the selected image should move to datalist2. How to do that? someone please help me,
You need to handle the ItemCommand event of one DataList in which you have to copy the selected data (image) into another dataSource of two DataList and remove that item from the datasource of one DataList.
Markup:
<asp:DataList
ID="DataList1"
runat="server"
OnItemCommand="PerformMove"
>
<ItemTemplate>
<br /><%#Eval("Text") %>
<asp:Button ID="btn1"
runat="server"
Text="Move"
CommandName="cmd"
CommandArgument='<%#Eval("Text") %>'
/>
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="DataList2" runat="server">
<ItemTemplate>
<br /><%#Eval("Text") %>
</ItemTemplate>
</asp:DataList>
Code-behind (.cs)
public class Data
{
public string Text { get; set; }
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Data> list1 = new List<Data >()
{
new Data() { Text="One"},
new Data() { Text="Two"},
new Data() { Text="Three"},
};
List<Data> list2 = new List<Data>();
Session["list1"] = list1;
Session["list2"] = list2;
DataList1.DataSource = Session["list1"];
DataList1.DataBind();
DataList2.DataSource = Session["list2"];
DataList2.DataBind();
}
}
protected void PerformMove(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "cmd")
{
List<Data> list1 = Session["list1"] as List<Data>;
List<Data> list2 = Session["list2"] as List<Data>;
list1.Remove(new Data() { Text=e.CommandArgument.ToString() });
list2.Add(new Data() { Text = e.CommandArgument.ToString() });
DataList1.DataSource = Session["list1"];
DataList1.DataBind();
DataList2.DataSource = Session["list2"];
DataList2.DataBind();
}
}
I am using this code and its working well for me.
ArrayList ImgArry = new ArrayList();
path = objGetBaseCase.GetImages(TotImgIds);
ImgArry.Add(SelImgId);
ImgArry.Add(SelImgpath);//image name
ImgArry.Add(SelImgName);//image path
//path.Remove(ImgArry);
List<ArrayList> t = new List<ArrayList>();
if (newpath.Count > 0)
t = newpath;
t.Add(ImgArry);
newpath = t;
for (int i = 0; i < newpath.Count; i++)
{
ArrayList alst = newpath[i];
newtb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);
}
dlstSelectedImages.DataSource = newtb;
DataBind();
path = objGetBaseCase.GetImages(TotImgIds);
for (int i = 0; i < path.Count; i++)
{
ArrayList alst = path[i];
tb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);
}
dlstImage.DataSource = tb;
DataBind();

Categories