Category Archives: .Net

Image is not displaying in master page

Issue : Image is not displaying in master page

Solution :

If you use html control in master page as like below line

<img src=”~/App_Themes/Images/company_logo.png” width=”203″ height=”36″></div>

then we want to include runat attribute inside the image tag.

<img src=”~/App_Themes/Images/company_logo.png” runat=”server”  width=”203″ height=”36″></div>

else change the html control to asp control, then it will work in the master page

Note :

  • If you use the ~/ syntax then the control has to be a server control;so we want to include runat in the tag.

Copy data from div to ClipboardData using Jquery

How to copy div content form div to clipboard

Code Behind File :

Create string builder with some content and assign as like

divcontent.InnerHtml = sbQuestionAndAnswers.ToString();

Design File:

 <div id=”divcontent” style=” width: 1px; height: 1px;overflow:hidden;” runat=”server”></div>

Script File :

if (window.clipboardData && clipboardData.setData) {
if ($(‘#ctl00_cphMain_divcontent’)) {
$(‘#ctl00_cphMain_divcontent’).show();
var editableDiv = $(‘#ctl00_cphMain_divcontent’)

[0];
var txtRange = document.body.createTextRange();
editableDiv.style.display = “”;
txtRange.moveToElementText(editableDiv);
txtRange.select();
txtRange.execCommand(“Copy”);
editableDiv.style.display = “none”;//Hide the div
}}

Note :

Copying the content of div which is bind dynamically form code-behind and it will not display in the page. From that we copy content to clipboard

Nullable Types

Nullable Types

Nullable types are variables that can be assigned with the value ‘null’. Allmost all value types can be declared as a nullable type. To declare a
value type as a nullable type, you have to add a questionmark after the type name.

For example:

char? a = null;
bool? b = null;
int? c = null;
double? d = null;

Nullable type has two read-only properties: HasValue and Value.
HasValue is a bool property. If the current value is ‘null’,
HasValue will return false, otherwise it will return true. The HasValue property can be used to test if a variable contains a value.

For Example :

int? test = 10;
if (test .HasValue)
{
Console.WriteLine(test .Value);
}
else
{
Console.WriteLine(“no value”);
}

How to convert Nullable Type to NON-Nullable Type

int? intValue1 = null;
int intValue2  = intValue1  ?? 10;

Total minutes between two time value

How to get the difference of two time and get MM:SS of  time

Code Behind :

 DateTime locCurrentDateTime = System.DateTime.Now;
TimeSpan difference = locCurrentDateTime.Subtract(Convert.ToDateTime(Session[“starttime”]));
double hrs = Math.Floor(difference.TotalMinutes);
double sec = difference.Seconds;
string time = new DateTime(difference.Ticks).ToString(“mm:ss”);

Note :

output for above code will be find total minutes between two time and formatted as MM:SS

Finding the lable value after clicking the linkbutton inside the gridview

Finding the lable/any control value after clicking the linkbutton inside the gridview

Code Behind File :

  protected void btnClick_Click(object sender, EventArgs e)
{

GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblID = (Label)clickedRow.FindControl(“lblEmpID”);

Session

[“patientEMRID”] = lblID.Text;

}

Note :

First line we finding the clickable row and then finding the label value inside the gridview. lblEmpID is the id of the lable .

Calling severside method form script

How to call server side method button click event from the client side script :

Script :

<%= Page.ClientScript.GetPostBackEventReference(btnClose, String.Empty) %>;

Note :

Place this code in the script to call the any sever-side method, from above btnclose is the click method of the button. and event is empty.

Calling Script method from server side method.

System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), “Script”, “ConfirmationAlert();”, true);

Note :

ConfirmationAlert()  method :

 function ConfirmationAlert() {
var copiedText = “”;
var answer = confirm(“Click ‘OK’, to give alert!”)
if (answer) {
alert(“You Click OK”);}}

Issue While exporting Gridview to Excel while deployment

Issue While exporting Gridview to Excel

 Issue    : Image is not showing in the Excel

 Solution : The URL must be

ImageUrl=”http://localhost:63360/Website/Images/help.gif” /> instead of ImageUrl=”~/help.gif”.

 So place URL in webcofig

<add key=”ImagePath” value=”http://localhost:63360/Website/Images/”/>

CodeBind :

imgStat.ImageUrl = ConfigurationSettings.AppSettings[“ImagePath”].ToString() + @”help.png”;

find the div inside the Gridview

How to find the div inside the Gridview (outside of gridview function)

.aspx file

<div id=”tooltip” style=”display: none;”></div>

Code Behind file

Make hide of the div

foreach (GridViewRow row in gvdStatus.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{

HtmlGenericControl dive = new HtmlGenericControl();
dive = ((HtmlGenericControl)(row.FindControl(“tooltip”)));
dive.Visible = false;
}
}

Applying color to the row based on the condition

if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Convert.ToInt32(e.Row.Cells

[2].Text) > 525)
{
e.Row.BackColor = System.Drawing.Color.Blue;
}
}

Note :

A table can have header data or footer rows. The above statement will make sure that the row is data row.
row.RowType == DataControlRowType.DataRow: use it every time if you want to look for something in every row.

Custom Paging with Numbers

Custom Paging with Numbers

.aspx File

<div>
PageSize:
<asp:DropDownList ID=”ddlPageSize” runat=”server” AutoPostBack=”true” OnSelectedIndexChanged=”PageSize_Changed”>
<asp:ListItem Text=”10″ Value=”10″ />
<asp:ListItem Text=”25″ Value=”25″ />
<asp:ListItem Text=”50″ Value=”50″ />
<asp:ListItem Text=”75″ Value=”75″ />
</asp:DropDownList>
<hr />
<asp:GridView ID=”gvCustomerDetails” runat=”server”>
</asp:GridView>
<br />
<asp:Button ID=”btnprev” Text=”<<” OnClick=”MovetoPrev” runat=”server” />
<asp:Repeater ID=”rptPage” runat=”server”>
<ItemTemplate>
<asp:LinkButton ID=”lnkPage” runat=”server” Text='<%#Eval(“Text”)%>’ CommandArgument='<%# Eval(“Value”) %>’
OnClick=”GettingPageIndex”></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID=”btnnext” Text=”>>” OnClick=”MovetoNext” runat=”server” />
</div>

.Cs
#region Using Namespaces
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using CustomerDetail;
using System.Web.UI.WebControls;
#endregion

public partial class GridViewPagingWithNumbers : System.Web.UI.Page
{
#region Private Constants
private const string SQL_CONNECTION = “Data Source=DBSRV;Initial Catalog=Shopping;User ID=sa;Password=sa”;
private const string SQL_SPNAME = “[sproc_GetCustomersDetails]”;
#endregion

#region Public Variables
public static int PAGE_NUMBER = 1;
public int RECORD_COUNT;
public static int PAGE_SIZE = 10;
#endregion

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadCustomerDetails();
}
}

#region Load Customer Records
private void LoadCustomerDetails()
{
var CustomerDetails = new List<CustomerDetails>();
#region Fetching and Loading the Customer Details
try
{
using (var sqlConn = new SqlConnection(SQL_CONNECTION))
{
using (var sqlCmd = new SqlCommand(SQL_SPNAME, sqlConn))
{
sqlCmd.Parameters.AddWithValue(“@PageNo”, PAGE_NUMBER);
sqlCmd.Parameters.AddWithValue(“@PageSize”, PAGE_SIZE);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
using (var sqlDataReader = sqlCmd.ExecuteReader())
{
while (sqlDataReader.Read())
{
CustomerDetails.Add(new CustomerDetails(Convert.ToInt32(sqlDataReader[“ID”]), Convert.ToString(sqlDataReader[“CustomerName”]),
Convert.ToString(sqlDataReader[“EmailID”]), Convert.ToString(sqlDataReader[“PhoneNo”])
));
}
sqlDataReader.NextResult();
sqlDataReader.Read();
RECORD_COUNT = Convert.ToInt32(sqlDataReader[“TotalRec”]);
}
}
gvCustomerDetails.DataSource = CustomerDetails.AsReadOnly();
gvCustomerDetails.DataBind();
this.CreatePages(RECORD_COUNT, PAGE_SIZE);
}
}
catch (Exception ex)
{
throw ex;
}
#endregion
}
#endregion

private void  CreatePages(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / decimal.Parse(ddlPageSize.SelectedValue));
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
pages.Add(new ListItem(“First”, “1”));
if (PAGE_NUMBER >= 10 && (PAGE_NUMBER) <= pageCount )
{
for (int loop_Index = PAGE_NUMBER-5; loop_Index < PAGE_NUMBER + 5; loop_Index++)
{
pages.Add(new ListItem(loop_Index.ToString(), loop_Index.ToString()));
}
}
else
{
for (int loop_Index = 1; loop_Index <= 10; loop_Index++)
{
pages.Add(new ListItem(loop_Index.ToString(), loop_Index.ToString()));
}

}

pages.Add(new ListItem(“Last”, pageCount.ToString()));
}
rptPage.DataSource = pages;
rptPage.DataBind();
}
protected void PageSize_Changed(object sender, EventArgs e)
{
PAGE_SIZE = Convert.ToInt32(ddlPageSize.SelectedValue);
PAGE_NUMBER = 1;
LoadCustomerDetails();
}
protected void GettingPageIndex(object sender, EventArgs e)
{
PAGE_NUMBER = int.Parse((sender as LinkButton).CommandArgument);
LoadCustomerDetails();
}
protected void MovetoNext(object sender, EventArgs e)
{
PAGE_NUMBER++;
LoadCustomerDetails();
}
protected void MovetoPrev(object sender, EventArgs e)
{
PAGE_NUMBER–;
LoadCustomerDetails();
}
}

CustomerDetails.cs

#region Using Namespaces
using System;
using System.Data;
using System.Configuration;
using System.Web;
#endregion

namespace CustomerDetail
{
public class ConnectionDetails
{
#region Public Method
public string ConnectionInfo
{
get
{
return ConfigurationSettings.AppSettings[“myConnectionString”].ToString();
}
}
#endregion
}

public class CustomerDetails
{
#region Private Members
private readonly int c_id;
private readonly string c_email;
private readonly string c_phoneNumber;
private readonly string c_name;
#endregion

#region Public Members
public int ID
{
get { return c_id; }
}
public string Name
{
get { return c_name; }
}
public string Email
{
get { return c_email; }
}
public string PhoneNumber
{
get { return c_phoneNumber; }
}
#endregion

#region Public Const.
public CustomerDetails(int pID, string pName, string pEmail, string pPhoneNumber)
{
c_id = pID;
c_email = pEmail;
c_name = pName;
c_phoneNumber = pPhoneNumber;
}
#endregion

}

}

Stored Procedure

ALTER PROCEDURE [dbo].[sproc_GetCustomersDetails]
@PageNo        INT,
@PageSize    INT
AS
BEGIN
SET NOCOUNT ON;

DECLARE @StartIndex INT, @EndIndex INT, @TotalRec INT, @TotalPages INT;

SELECT @TotalRec = COUNT(1) FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL;

IF @PageNo <= 0 SET @PageNo = 1;
IF @PageSize <= 0 SET @PageSize = 1;
IF @PageSize > @TotalRec SET @PageSize = @TotalRec;

SET @TotalPages = CEILING(@TotalRec * 1.0 / @PageSize);
IF (@PageNo > @TotalPages) SET @PageNo = @TotalPages;

SET @StartIndex = (@PageNo – 1) * @PageSize + 1;
SET @EndIndex =  @StartIndex + @PageSize – 1;

IF @StartIndex > @TotalRec SET @StartIndex = @TotalRec;
IF @EndIndex > @TotalRec SET @EndIndex = @TotalRec;

WITH [Customer] AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [CustomerName] ASC) AS [RowNo], [ID]
FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL
)
SELECT
[I].[ID],
[I].[CustomerName],
[I].[EmailID],
[I].[PhoneNo]
FROM [tCustomer] AS [I] WITH (NOLOCK)
INNER JOIN [Customer] AS [II] WITH (NOLOCK) ON [II].[RowNo] BETWEEN @StartIndex AND @EndIndex AND [II].[ID] = [I].[ID]
ORDER BY [II].[RowNo] ASC;

SELECT @TotalPages AS [TotalPages], @TotalRec AS [TotalRec];
END;