Thursday, May 10, 2012

how to prevent Function Repetition in page refresh using c# asp.net


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) // If page loads for first time
    {
        // Assign the Session["update"] with unique value
        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
        //=============== Page load code =========================




        //============== End of Page load code ===================
    }
}

protected void btnDisplay_Click(object sender, EventArgs e)
{ 
    // If page not Refreshed
    if (Session["update"].ToString() == ViewState["update"].ToString())
    {
        //=============== On click event code ========================= 

        lblDisplayAddedName.Text = txtName.Text;

        //=============== End of On click event code ==================

        // After the event/ method, again update the session 

        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
    }
    else // If Page Refreshed
    {
        // Do nothing 
    }
}

protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);
  ViewState["update"] = Session["update"];
}     

Sunday, May 6, 2012

Golden Roles For Dynamic Control Creation in Asp.net


1. Make sure your dynamic controls are Loaded on every postback.

Lets play with a very simple example,

ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

   

   < body > 
     < form id="form1" runat="server" > 
     < div >
         < asp:PlaceHolder ID="PlaceHolder1" runat="server"  >   < /asp:PlaceHolde > 
         < asp:Button ID="Button1" runat="server" Text="Button" /  >
     < /div  >  
     < /form  >  
< /body  >  
< /html>

C# Code Behind
public partial class _Default : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
        this.PlaceHolder1.Controls.Add(t);        
    }
}

The above code works fine, but a common mistake is to try to conditionally load dynamic controls, if we tweak the code a little bit you will notice we loose our TextBox after any postback. The following code will not load the TextBox after our first postback.

public partial class _Default : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {      
       if (!IsPostBack)         {
            TextBox t = new TextBox();
            t.ID = "textBox";
            this.PlaceHolder1.Controls.Add(t);
        }
    }
}
Its recommended to load the dynamic controls during the Page_Init instead, because we may want to hook up our events with proper handler at an early stage.
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)     {
        TextBox t = new TextBox();
        t.ID = "textBox";
        t.TextChanged+=new EventHandler(t_TextChanged);
        this.PlaceHolder1.Controls.Add(t);
    }
}

2. Do not assigning properties of a dynamic control (viewstate enabled), during Page_Init, it will not be reflected.

Here is scenario of another common mistake, "123" assigned to the Text property during Page_Init,
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = "textBox";
       t.Text = "123";         this.PlaceHolder1.Controls.Add(t);
    }
}
controllifecycle
the above code will not work because, Initialization happens before LoadViewState during the control lifecycle. The value assigned to the properties during Initialization will simply get overwritten by the ViewState values.

3. If you are expecting your ViewState to retain after the postback, always assign same ID to the dynamic control
The following piece of code will not work, as I am assigning a new ID to the dynamic control after each postback. The LoadViewState retrieves previously saved viewstate data using the control ID, as the control ID has changed, it doesn't know anymore what to load, as a result it cannot load previously saved viewstate data any more.
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox t = new TextBox();
        t.ID = Guid.NewGuid().ToString();
        this.form1.Controls.Add(t);       
    }
}

Thursday, April 26, 2012

how to get print mode and export the controls using javascript

 <script type="text/javascript">


             function printdiv(printpage)
              {
                 var headstr = "";

                 var footstr = "";
                 var newstr = document.all.item(printpage).innerHTML;
                 var oldstr = document.body.innerHTML;
                 document.body.innerHTML = headstr + newstr + footstr;
                 window.print();
                 document.body.innerHTML = oldstr;
                 return false;
             }

     < /script>



    < input type="button" value="print" onclick="printdiv('print_area');" />

Friday, March 30, 2012

Updating Data Sources with DataAdapters (ADO.NET)

private void AdapterUpdate(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))

{
SqlDataAdapter dataAdpater = new SqlDataAdapter("SELECT [Emp_ID], [User_Name], [Level], [Email_ID], [User_Full_Name], [Is_Active] FROM [LOGIN]",connection);

dataAdpater.UpdateCommand = new SqlCommand("UPDATE [LOGIN] SET [User_Name] = @User_Name " + "WHERE Emp_ID = @Emp_ID", connection);

dataAdpater.UpdateCommand.Parameters.Add("@User_Name", SqlDbType.NVarChar, 15,"User_Name");

SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add("@Emp_ID", SqlDbType.Int);
parameter.SourceColumn = "Emp_ID";
parameter.SourceVersion = DataRowVersion.Original;

DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);

DataRow categoryRow = categoryTable.Rows[0];
categoryRow["User_Name"] = "sivaji the boss";

dataAdpater.Update(categoryTable);



Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}

Thursday, March 8, 2012

how to create new window in response.write fn in c#

Response.Write("<script language=javascript>window.open('./image/"+btn.CommandArgument+"','win','toolbar=0,location=0,directories=0,status=1, menubar=1,scrollbars=1,resizable=1,"+"width=600,height=600');</script>");


we can useany url in the part of(./image/"+btn.CommandArgument+")

Wednesday, February 8, 2012

how to convert amount number to text format in c#

protected void Page_Load(object sender, EventArgs e)
{
string sdfdsf = retWord(545150569);
}

public string retWord(int number)

{

if (number == 0)

return "Zero";

if (number == -2147483648) return "Minus Two Hundred and Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred and Forty Eight";

int[] num = new int[4];

int first = 0;

int u, h, t;

System.Text.StringBuilder sb = new System.Text.StringBuilder();

if (number < 0)

{

sb.Append("Minus ");

number = -number;

}

string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " };

string[] words = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };

string[] words2 = { "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };

string[] words3 = { "Thousand ", "Lakh ", "Crore " };

num[0] = number % 1000; // units

num[1] = number / 1000;

num[2] = number / 100000;

num[1] = num[1] - 100 * num[2]; // thousands

num[3] = number / 10000000; // crores

num[2] = num[2] - 100 * num[3]; // lakhs



for (int i = 3; i > 0; i--)

{

if (num[i] != 0)

{

first = i;

break;

}

}

for (int i = first; i >= 0; i--)

{

if (num[i] == 0) continue;

u = num[i] % 10; // ones

t = num[i] / 10;

h = num[i] / 100; // hundreds

t = t - 10 * h; // tens

if (h > 0) sb.Append(words0[h] + "Hundred ");

if (u > 0 || t > 0)

{

if (h > 0 || i == 0) sb.Append("and ");

if (t == 0)

sb.Append(words0[u]);

else if (t == 1)

sb.Append(words[u]);

else

sb.Append(words2[t - 2] + words0[u]);

}

if (i != 0) sb.Append(words3[i - 1]);

}

return sb.ToString().TrimEnd();

}
}

Tuesday, January 24, 2012

how to display a loading process image in asp.net functions

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args)
{
document.getElementById('<%= lblmsg.ClientID %>').style.display = 'none';

var state = document.getElementById('loadingdiv').style.display;
if (state == 'block') {
document.getElementById('loadingdiv').style.display = 'none';
} else {
document.getElementById('loadingdiv').style.display = 'block';
}
args.get_postBackElement().disabled = true;
}
</script>


<div id="loadingdiv" style="display:none; margin-left:5.3em">
<img src="icons/throbber_circle.gif" alt="Loading" /> Please wait...
</div>
<asp:Label ID="lblmsg" runat="server" ForeColor="Green"></asp:Label>

Sunday, January 1, 2012

how to set a linkbutton as default button in asp.net using javascript

txtPassword.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnLogin.UniqueID + "','')");

Monday, October 10, 2011

How to add arraylist inside of the arraylist in asp.net

ArrayList xxx = new ArrayList();


//////////////Adding inside of arraylist////////////////

for (int g = 1; g <= dt.Rows.Count; g++)
{
xxx.Add(new ArrayList());

}


/////////////////reading the arraylist inside of arraylist/////////////////

for (int g = 0; g < dt.Rows.Count; g++)

{
(xxx[g] as ArrayList).Add(dt2.Rows[j][1+g].ToString());

}

Tuesday, October 4, 2011

How to import data from excel to datatable in c#

protected void button1_Click(object sender, EventArgs e)
{
DataTable test = getDataFromXLS("c:\\xl2xml.xls");
if (test != null)
grid.DataSource = test;
grid.DataBind();
}


protected DataTable getDataFromXLS(string strFilePath)
{
try
{
string strConnectionString = "";
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + strFilePath + "; Jet OLEDB:Engine Type=5;" +
"Extended Properties=Excel 8.0;";
OleDbConnection cnCSV = new OleDbConnection(strConnectionString);
cnCSV.Open();
OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [Insurance_Aging$]", cnCSV);
OleDbDataAdapter daCSV = new OleDbDataAdapter(); daCSV.SelectCommand = cmdSelect;
DataTable dtCSV = new DataTable();
daCSV.Fill(dtCSV);
cnCSV.Close();
daCSV = null;
return dtCSV;
}
catch (Exception ex)
{
return null;
}
finally { }
}



Import Excel to DataTable
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=911149&SiteID=1
http://support.microsoft.com/kb/815142/en-us
http://msdn2.microsoft.com/en-us/library/ms178685.aspx
http://support.microsoft.com/kb/306572/
http://samples.gotdotnet.com/quickstart/aspplus/doc/configformat.aspx
http://support.microsoft.com/kb/316675/en-us http://msdn.microsoft.com/library/default.asp?url=/library/en-

Sunday, September 25, 2011

bulk import from excel to sql using c#

public partial class _Default : System.Web.UI.Page
{
string strConnection = ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//Create connection string to Excel work book
string excelConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Details.xls;
Extended Properties=""Excel 8.0;HDR=YES;""";

//Create Connection to Excel work book
OleDbConnection excelConnection =
new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select [ID],[Name],[Location] from [Detail$]",
excelConnection);

excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();

SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Details";
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
}
}

how to read excel sheet cells using c#

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnupload_Click(object sender, EventArgs e)
{


Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ;

string str=string.Empty;
int rCnt = 0;
int cCnt = 0;

HttpPostedFile file = upload.PostedFile;
string fileExt = Path.GetExtension(file.FileName).ToLower();
string fileName = Path.GetFileName(file.FileName);
string filepath = Server.MapPath("./importedfiles/") + fileName;

if (fileExt == ".xls" || fileExt == ".xlsx")
{
if (File.Exists(filepath))
File.Delete(filepath);

file.SaveAs(Server.MapPath("./importedfiles/") + fileName);
//MessageBox.Show(" " + d + " Successfully Uploaded");
}

xlApp = new Excel.ApplicationClass();

xlWorkBook = xlApp.Workbooks.Open("" + filepath + "", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

range = xlWorkSheet.UsedRange;

for (rCnt = 2; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{

if ((range.Cells[rCnt, cCnt] as Excel.Range).Value == null)
{
if (cCnt == 1)
{
str +=" ";
}
else
{
str +=","+" ";
}

}
else
{
if (cCnt == 1)
{
str += (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value.ToString();
}
else
{
str += "," + (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value.ToString();
}

}


}
}

xlWorkBook.Close(true, null, null);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}

private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
// MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();

}
}

}

Tuesday, September 6, 2011

How to get the date of a day from today

DateTime MyDate;
MyDate = Convert.ToDateTime(DateTime.Now);
MyDate = MyDate + TimeSpan.FromDays(7);
string ss = Convert.ToString(MyDate);

Thursday, June 30, 2011

How to implement embedded media player in asp.net c#

Java Script Alert - Run with asp.net update panel

string alertScript = "javascript: alert('Error Occured, Please try again later')";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript",
alertScript, true);

Friday, June 24, 2011

Export to word from gridview in c#

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Individual report of user" + " " + ddlagent.SelectedItem.Text + ".doc"));
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
getgrid();
//Change the Header Row back to white color
//Applying stlye to gridview header cells
DataList1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();


}

Export to Excel from gridview in c#

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
if (chkall.Checked == true)
{
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "calls report of alluser"+txtfromdate.Text+" "+"to"+" "+txttodate.Text+".xls"));
}
else
{
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "calls report of user" + " " + ddlagent.SelectedItem.Text + ".xls"));
}
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
reportgrid.AllowPaging = false;
getgrid();
//Change the Header Row back to white color
reportgrid.HeaderRow.Style.Add("background-color", "#afabc4");
//Applying stlye to gridview header cells
for (int i = 0; i < reportgrid.HeaderRow.Cells.Count; i++)
{
reportgrid.HeaderRow.Cells[i].Style.Add("background-color", "#afabc4");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in reportgrid.Rows)
{
gvrow.BackColor = Color.White;
if (j <= reportgrid.Rows.Count)
{
//if (j % 2 != 0)
//{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#FFFFFF");
}
//}
}
j++;
}

reportgrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();



}

Sunday, June 19, 2011

How to Remove Rendering Function error from asp.net c# program???

Disable the event validations in asp.net page using below:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="Reports.aspx.cs" Inherits="Reports" %>

And Override the Rendering Verification function in c#:


public override void VerifyRenderingInServerForm(Control control)
{

}

Thursday, June 16, 2011

how to execute audio converters using System.Diagnostics in c#(GoldWave)

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo stratInfo = new System.Diagnostics.ProcessStartInfo();
stratInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
stratInfo.FileName = "C:\\Program Files\\GoldWave\\Goldwave.exe";
//stratInfo.Arguments = "/C copy /b image1.jpg + Archive.rar image2.jpg";
stratInfo.Arguments = "/process:MP3 C:\Users\jaganath\Desktop\bosco.VC2";

process.StartInfo = stratInfo;
process.Start();