Redirect to previous page

ViewState[“PrevPage”] = Request.UrlReferrer.ToString();

Block page while asynchronous post back asp.net

Method I:

Style:

<style type=”text/css”>
.hide
{
display: none;
}
.show
{
display: inherit;
}
.progressBackgroundFilter
{

position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
overflow: hidden;
padding: 0;
margin: 0;
background-color: #000;
filter: alpha(opacity=40);
opacity: 0.5;
z-index: 1000;
}
.processMessage
{
border-color: #808080;
border-style: solid;
border-width: 0px 1px;

position: absolute;
font-family: arial,helvetica,clean,sans-serif, Verdana;
font-size:12px;
font-weight:normal;
color:#000066;
top: 45%;
left: 43%;
padding: 10px;
width: 18%;
z-index: 1001;
background-color: #fff;
}
</style>

 

In ASPX Source:

<asp:UpdateProgress ID=”updPrgsBaselineTab” runat=”server”>
<ProgressTemplate>
<div id=”progressBackgroundFilter”>
</div>
<div id=”processMessage”>
<table width=”100%”>
<tr style=”width: 100%”>
<td style=”width: 100%”>
Please Wait……….
</td>
</tr>
<tr style=”width: 100%”>
<td style=”width: 100%” align=”center”>
<img src=”images/activity.gif” alt=”Loading…” />
</td>
</tr>
</table>
</div>
</ProgressTemplate>
</asp:UpdateProgress>

—————————————————-

Method II:

Style:

.PrProgress
{

display: block;
position: absolute;
padding: 2px 3px;
}
.PrContainer
{
border: solid 1px #808080;
border-width: 1px 0px;
}
.PrHeader
{

background: url(Images/sprite.png) repeat-x 0px 0px;
border-color: #808080 #808080 #ccc;
border-style: solid;
border-width: 0px 1px 1px;
padding: 0px 10px;
color: #000000;
font-size: 9pt;
font-weight: bold;
line-height: 1.9;
white-space:nowrap;
font-family: arial,helvetica,clean,sans-serif;
}
.PrBody
{
background-color: #f2f2f2;
border-color: #808080;
border-style: solid;
border-width: 0px 1px;
padding: 10px;
}

In ASPX Source:

<div id=”pnlPopup” style=”display: none;”>
<div id=”innerPopup”>
<div>
Loading, please wait…</div>
<div>
<img width=”220px” height=”19px” src=”images/activity.gif” alt=”loading…” />
</div>
</div>

 

Source: http://www.codekicks.com/2010/06/how-to-block-aspnet-page-while-ajax.html

 

CheckboxList Selected items in javascript Asp.net

function CheckBoxSelectedCount()

{

var tableBody = document.getElementById(‘<%=ChkBox_Zones.ClientID %>’);

var status=0;

for(var i=0;i<tableBody.cells.length;i++)

{

var checkBox = document.getElementById(tableBody.id + ‘_’ + [i]);

if(checkBox!=null && checkBox.checked){ numItemsChecked = numItemsChecked + 1; }

 }

if(numItemsChecked ==0)

{

alert (‘Please Select Zones’);

tableBody.focus();

return false ;

}

return true ;

}

Handle Multiple click on button click

<head runat=”server”>
<script language = “javascript”>
var c=0;
function DisableClick()
{
var objName = ‘Button1’;
document.getElementById(objName).disabled=true;
c=c+1;
msg = ‘Please Wait…(‘+ c +’)!’;
document.getElementById(objName).value= msg;
var t=setTimeout(‘DisableClick()’,1000);
}
</script>
</head>

=====================================

Button Control – HTML Button instead of Asp button.
<INPUT id=”Button1″
onclick=”DisableClick();” type=”button”
value=”Submit Payment” name=”Button1″
runat=”server” onserverclick=”Button1_Click”>

==========================================

Codebehind:

protected void Button1_Click(object sender, EventArgs e)
{
ArrayList a = new ArrayList();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 1000; j++)
{
a.Add(i.ToString() + j.ToString());
}
}
Response.Write(“I am done: ” +
DateTime.Now.ToLongTimeString());
}

======================================================

Source: http://dotnetguts.blogspot.com/2008/05/disable-multiple-button-click-in-aspnet.html

======================================================

****************************************************

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<script type=”text/javascript”>
var pbControl = null;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
pbControl = args.get_postBackElement();  //the control causing the postback
pbControl.disabled = true;
}
function EndRequestHandler(sender, args) {
pbControl.disabled = false;
pbControl = null;
}
</script>

<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<ContentTemplate>
<table border=”1″ cellpadding=”2″ cellspacing=”2″>
<tr>
<td style=”width:25%”></td>
<td style=”width:25%”></td>
<td style=”width:25%”></td>
<td style=”width:25%”></td>
</tr>
<tr>
<td></td>
<td align=”right”>Name:</td>
<td>
<asp:TextBox ID=”txt_name” runat=”server”></asp:TextBox>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td align=”right”>Password:</td>
<td>
<asp:TextBox ID=”txt_pwd” runat=”server”></asp:TextBox>
</td>
<td></td>
</tr>
<tr>
<td colspan=”4″>
<asp:Button ID=”btn_insert” runat=”server” Text=”Insert”
OnClientClick=”return validateSave();” onclick=”btn_insert_Click”/>
</td>
</tr>

</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″>
<ProgressTemplate>
Loading…
</ProgressTemplate>
</asp:UpdateProgress>

Code Behind:

———————–

protected void btn_insert_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}

Source: http://disturbedbuddha.wordpress.com/2007/12/10/disabling-a-trigger-control-during-asynchronous-postback/

==============================================================

Stored Procedure Example with code and query

public SqlConnection DBConnect()

{

try

{

con = new SqlConnection(ConnectionStr);

if (con.State != ConnectionState.Open)

{

con.Open();

}

return con;

}

catch (Exception)

{

throw;

}

}

public string ExecScalar(string ProcedureName, SqlParameter[] @Param)

{

try

{

com = new SqlCommand(ProcedureName, DBConnect());

com.CommandType = CommandType.StoredProcedure;

for (int i = 0; i < @Param.Length; i++)

{

com.Parameters.Add(@Param[i]);

}

return Convert.ToString(com.ExecuteScalar());

}

catch (Exception)

{

throw;

}

finally

{

con.Close();

}

}

public int ExecQryProcedure(string ProcedureName, SqlParameter[] @Param)

{

try

{

com = new SqlCommand(ProcedureName, DBConnect());

com.CommandType = CommandType.StoredProcedure;

for (int i = 0; i < @Param.Length; i++)

{

com.Parameters.Add(@Param[i]);

}

return com.ExecuteNonQuery();

}

catch (Exception)

{

throw;

}

finally

{

con.Close();

}

}

public DataSet FillDatasetProcedure(string ProcedureName)

{

try

{

com = new SqlCommand(ProcedureName, DBConnect());

da = new SqlDataAdapter(com);

com.CommandType = CommandType.StoredProcedure;

ds = new DataSet();

da.Fill(ds);

return ds;

}

catch (Exception)

{

throw;

}

finally

{

con.Close();

}

}

public DataSet FillDatasetProcedureParam(string ProcedureName, SqlParameter[] @Param)
{
try
{
com = new SqlCommand(ProcedureName, DBConnect());
da = new SqlDataAdapter(com);
com.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < @Param.Length; i++)
{
com.Parameters.Add(@Param[i]);
}
ds = new DataSet();
da.Fill(ds);
return ds;
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}

Call Functions:

public int UpdateRequest(Int64 RequestID, string PersonI, string PersonII, string PersonIII)

{

try

{

@params = new SqlParameter[4];

@params[0] = new SqlParameter(“@RequestID”, RequestID);

@params[1] = new SqlParameter(“@PersonI”, PersonI);

@params[2] = new SqlParameter(“@PersonII”, PersonII);

@params[3] = new SqlParameter(“@PersonIII”, PersonIII);

return Ebiz.ExecQryProcedure(“UpdateRequestAuthority”, @params);

}

catch (Exception)

{

throw;

}

}

public DataSet RetrieveAll(string Dept,string LoginCode)
{
try
{
@params = new SqlParameter[2];
@params[0] = new SqlParameter(“@DEPARTMENT”, Dept);
@params[1] = new SqlParameter(“@LoginCode”, LoginCode);
return Ebiz.FillDatasetProcedureParam(“FetchAllEmployee_Name_Designation_Mail_Code”, @params);
}
catch (Exception)
{

throw;
}
}

public int RetrieveCount(string EmpCode)
{
try
{
@params = new SqlParameter[1];
@params[0] = new SqlParameter(“@LoginEmpCode”, EmpCode);
return Convert.ToInt32(Ebiz.ExecScalar(“FetchAllProcessDetailCount”, @params));
}
catch (Exception)
{

throw;
}
}


Stored Procedure:

I.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE procedure [dbo].[FetchAllEmployee_Name_Code_Mail]
@DEPARTMENT varchar(150)

as
begin

SELECT FS_CANDIDATENAME + ‘  (‘ + FS_EMAILID + ‘)’  as ‘Name_Mail’,FS_EMPCODE as ‘code’
FROM
TCANDIDATEINFO
WHERE
FS_STATUS=’Interviewed and joined’ AND (FS_DEPARTMENT=@DEPARTMENT OR FS_DEPARTMENT=’CORPORATE’)
ORDER BY FS_CANDIDATENAME

End

II.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE procedure [dbo].[FetchAllRequestAuthority_Name_Code_Mail]
as begin
declare @TotalRows numeric
declare @CntFlag numeric
declare @requestid numeric
declare @PersonIcode varchar(100)
declare @PersonIIcode varchar(100)
declare @PersonIIIcode varchar(100)

declare @RequestID1 numeric
declare @RequestType varchar(100)

declare @Name_Mail1 varchar(500)
declare @EMPCODE1 varchar(500)

declare @Name_Mail2 varchar(500)
declare @EMPCODE2 varchar(500)

declare @Name_Mail3 varchar(500)
declare @EMPCODE3 varchar(500)

IF EXISTS(SELECT name FROM sys.tables  WHERE name = ‘#RequestAuthority_NameCodeDesigMail’)–
DROP TABLE #RequestAuthority_NameCodeDesigMail

create table #RequestAuthority_NameCodeDesigMail (RequestType varchar(500),RequestID numeric,Name_Mail1 varchar(500),EMPCODE1 varchar(500),Name_Mail2 varchar(500),EMPCODE2 varchar(500),Name_Mail3 varchar(500),EMPCODE3 varchar(500))

select @TotalRows= count(*) from master_requestauthority
set @CntFlag=1
while (@CntFlag<=@TotalRows)
begin
select @requestid=a.requestid,@PersonIcode=personi,@PersonIIcode=personii,@PersonIIIcode=personiii from MASTER_REQUESTAUTHORITY a where
@CntFlag=(select count(*) from MASTER_REQUESTAUTHORITY b where a.requestid >= b.requestid)

SELECT     @RequestType=A.RequestType, @RequestID1=@requestid
FROM         MASTER_REQUESTTYPE a inner join MASTER_REQUESTAUTHORITY b ON a.requestid = b.requestid where b.requestid=@requestid

SELECT     @Name_Mail1=a.FS_CANDIDATENAME + ‘  (‘ + a.FS_EMAILID + ‘)’,@EMPCODE1=@PersonIcode
FROM         TCANDIDATEINFO a inner join master_requestauthority b
ON a.Fs_EmpCode = b.PersonI  where b.requestid=@requestid

SELECT     @Name_Mail2=a.FS_CANDIDATENAME + ‘  (‘ + a.FS_EMAILID + ‘)’,@EMPCODE2=@PersonIIcode
FROM         TCANDIDATEINFO a inner join master_requestauthority b
ON a.Fs_EmpCode = b.PersonII  where b.requestid=@requestid

SELECT     @Name_Mail3=a.FS_CANDIDATENAME + ‘  (‘ + a.FS_EMAILID + ‘)’,@EMPCODE3=@PersonIIIcode
FROM         TCANDIDATEINFO a inner join master_requestauthority b
ON a.Fs_EmpCode = b.PersonIII  where b.requestid=@requestid

insert into #RequestAuthority_NameCodeDesigMail values(@RequestType,@requestid1,@Name_Mail1,@EMPCODE1,@Name_Mail2,@EMPCODE2,@Name_Mail3,@EMPCODE3)

set @CntFlag=@CntFlag + 1
set @requestid =null
set @PersonIcode =”
set @PersonIIcode =”
set @PersonIIIcode =”

set @RequestID1 =null
set @RequestType =”

set @Name_Mail1 =”
set @EMPCODE1=null

set @Name_Mail2 =”
set @EMPCODE2 =null

set @Name_Mail3 =”
set @EMPCODE3 =null
end

select RequestType,RequestID,Name_Mail1 as ‘Person1NameMail’,EMPCODE1 as ‘Person1Code’, Name_Mail2 as ‘Person2NameMail’,EMPCODE2 as ‘Person2Code’,Name_Mail3 as ‘Person3NameMail’,EMPCODE3 as ‘Person3Code’ from #RequestAuthority_NameCodeDesigMail
End

DropDownList

Fill DropDownList

public SqlConnection DBConnect()
{
try
{
con = new SqlConnection(ConnectionStr);
if (con.State != ConnectionState.Open)
{
con.Open();
}
return con;
}
catch (Exception)
{

throw;
}

}

private void FillRequestType()

{

try

{

ds = new DataSet();
ds.Clear();
da = new SqlDataAdapter(Qry, DBConnect());
da.Fill(ds);
con.Close();

Ddl_RequestTypeAuthority.DataSource = ds;

Ddl_RequestTypeAuthority.DataTextField = “RequestType“;

Ddl_RequestTypeAuthority.DataValueField = “DepartmentID“;

Ddl_RequestTypeAuthority.DataBind();

Ddl_RequestTypeAuthority.Items.Insert(0, “Select”);

}

catch (Exception)

{

throw;

}

}

Bind an XML to DropDownList ASP.Net C#

Employees.xml

<Employees >
<Employee >
<Name >David </Name >
<ID >101 </ID >
<IsActive >true </IsActive >
</Employee >
<Employee >
<Name >Tom </Name >
<ID >102 </ID >
<IsActive >true </IsActive >
</Employee >
<Employee >
<Name >Rick </Name >
<ID >103 </ID >
<IsActive >false </IsActive >
</Employee >
<Employee >
<Name >Mark </Name >
<ID >104 </ID >
<IsActive >true </IsActive >
</Employee >
</Employees >

——————————————————–

Code sample:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath(“Employees.xml”));

DataView DV = DS.Tables[“Employee”].DefaultView;
DV.RowFilter = “IsActive=’true’”;
DV.Sort = “Name asc”;

DropDownList1.DataSource = DV;
DropDownList1.DataValueField = “ID”;
DropDownList1.DataTextField = “Name”;
DropDownList1.DataBind();
}
}

Focus Dropdownlist ListItem Dynamically


Ddl_Auth.SelectedIndex = Ddl_Auth.Items.IndexOf(Ddl_Auth.Items.FindByText(GridView_Authority.SelectedRow.Cells[4].Text.Trim()));

Export DataSet To Excel C# & VB.Net

aspx.cs

protected void btn_Excel_Click(object sender, EventArgs e)
{
try
{
if (txt_Code.Text != “” )
{
Ds = new DataSet();
Ds.Clear();

BL.EmpCode = txt_Code.Text;

Ds = DL.FillCondition(BL);
Obj.ExportToExcel(Ds, “EmployeeReport-Code:” + txt_Code.Text);
}
else
{
lbl_status.Text = “Enter Date”;
lbl_status.CssClass = “lblStatusException”;
lbl_status.Visible = true;
}
}
catch (Exception)
{
lbl_status.Text = “Error in Excel generation”;
lbl_status.CssClass = “lblStatusException”;
lbl_status.Visible = true;
}
}

.cs

public void ExportToExcel(DataSet DsExcel, String XLname)
{
try
{
DataTable dt = DsExcel.Tables[0];
//DataTable dt = DsExcel;

string attachment = “attachment; filename=” + XLname + “.xls”;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader(“content-disposition”, attachment);
HttpContext.Current.Response.ContentType = “application/vnd.ms-excel”;
string tab = “”;
foreach (DataColumn dc in dt.Columns)
{
HttpContext.Current.Response.Write(tab + dc.ColumnName);
tab = “\t”;
}
HttpContext.Current.Response.Write(“\n”);
int i;
foreach (DataRow dr in dt.Rows)
{
tab = “”;
for (i = 0; i < dt.Columns.Count; i++)
{
HttpContext.Current.Response.Write(tab + dr[i].ToString());
tab = “\t”;
}
HttpContext.Current.Response.Write(“\n”);
}
HttpContext.Current.Response.End();

}
catch (Exception)
{
throw;
}
}

Export CurrentPage of Gridview into Excel

 

protected void btn_ExcelExport_Click(object sender, EventArgs e)
{
try
{
obj.ExportToExcel(Grid_Report, “Bills_Report_” + DateTime.Now.ToString(“dd/MM/yyyy”));
Response.End();
}
catch (Exception ex)
{
lbl_Status.Visible = true;
lbl_Status.ForeColor = Color.Red;
lbl_Status.Text = “Exception occured: ” + ex.Message.ToString();
}
}

public override void VerifyRenderingInServerForm(Control control)
{

}

If the Grid is in UpdatePanel, add Trigger to the Exporting Button

<Triggers>
<asp:PostBackTrigger ControlID=”btn_ExcelExport” />
</Triggers>

public void ExportToExcel(GridView gv, string XLname)
{
try
{
//HttpContext.Current.Response.Write(fileName);

HttpContext.Current.Response.ContentType = “application/excel”;

HttpContext.Current.Response.AppendHeader(“Content-Disposition”, “attachment; filename=” + XLname + “”);

System.IO.StringWriter sw = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter hsw = new System.Web.UI.HtmlTextWriter(sw);

gv.RenderControl(hsw);

HttpContext.Current.Response.Write(sw.ToString());
}
catch (Exception)
{
throw;
}
}

===========================

FileName:  Logics.cs

/// <summary>
///
/// </summary>
/// <param name=”fileName”></param>
/// <param name=”gv”></param>
public static void ExportToExcelCurrentPage(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
“content-disposition”, string.Format(“attachment; filename={0}”, fileName));
HttpContext.Current.Response.ContentType = “application/ms-excel”;

using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
//  Create a form to contain the grid
Table table = new Table();

//  add the header row to the table
if (gv.HeaderRow != null)
{
Logics.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}

//  add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
Logics.PrepareControlForExport(row);
table.Rows.Add(row);
}

//  add the footer row to the table
if (gv.FooterRow != null)
{
Logics.PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}

//  render the table into the htmlwriter
table.RenderControl(htw);

//  render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}

/// <summary>
/// Replace any of the contained controls with literals
/// </summary>
/// <param name=”control”></param>

private static void PrepareControlForExport(Control control)

{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? “True” : “False”));
}

if (current.HasControls())
{
Logics.PrepareControlForExport(current);
}
}
}

VB.net

Public Sub ExportDataSetToExcel(ByVal dt As DataTable, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
‘ first let’s clean up the response.object
response.Clear()
response.Charset = “”
‘ set the response mime type for excel
response.ContentType = “application/vnd.ms-excel”
response.AddHeader(“Content-Disposition”, “attachment;filename=””” & filename & “”””)
‘ create a string writer
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
‘ instantiate a datagrid
Dim dg As New GridView()
dg.AllowPaging = False
dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub