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 + "','')");