Monday, July 15, 2013

Disable button and show loading message while user clicked in asp.net c# USING UpdatePanel

After the ScriptManager put follow script on the page
 

<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>

Monday, July 8, 2013

How to switch or add or move listbox item to another listbox items using javascript in asp.net C#

I believe, most of the developers will encounter the situation that in two list boxes, we like move listbox item to another listbox.
There is no issue if we are using C#. But, as we've known, there could be better if we can use javascript and it can reduce roundtrips (server-client) for every single time in clicking move button.
It is lightweight and user friendly. I have added one more good function that user can order the list as their own.
Below is the complete javascript.

<script type="text/javascript" language="javascript">
        function listbox_move(listID, direction) {
 

            var listbox = document.getElementById('<%= d.ClientID %>');
            var selIndex = listbox.selectedIndex;

            if (-1 == selIndex) {
                alert("Please select an option to move.");
                return;
            }

            var increment = -1;
            if (direction == 'up')
                increment = -1;
            else
                increment = 1;

            if ((selIndex + increment) < 0 ||
                (selIndex + increment) > (listbox.options.length - 1)) {
                return;
            }

            var selValue = listbox.options[selIndex].value;
            var selText = listbox.options[selIndex].text;
            listbox.options[selIndex].value = listbox.options[selIndex + increment].value
            listbox.options[selIndex].text = listbox.options[selIndex + increment].text

            listbox.options[selIndex + increment].value = selValue;
            listbox.options[selIndex + increment].text = selText;

            listbox.selectedIndex = selIndex + increment;
        }

        function listbox_moveacross(SwapDirection) {
            if (SwapDirection == 'add') {
                var src = document.getElementById('<%= s.ClientID %>');
                var dest = document.getElementById('<%= d.ClientID %>');
            }
            else {
                var src = document.getElementById('<%= d.ClientID %>');
                var dest = document.getElementById('<%= s.ClientID %>');
            }
            for (var count = 0; count < src.options.length; count++) {

                if (src.options[count].selected == true) {
                    var option = src.options[count];

                    var newOption = document.createElement("option");
                    newOption.value = option.value;
                    newOption.text = option.text;
                    newOption.selected = true;
                    try {
                        dest.add(newOption, null); //Standard
                        src.remove(count, null);
                    } catch (error) {
                        dest.add(newOption); // IE only
                        src.remove(count);
                    }
                    count--;

                }

            }

        }
        function listbox_selectall(listID, isSelect) {

            var listbox = document.getElementById(listID);
            for (var count = 0; count < listbox.options.length; count++) {

                listbox.options[count].selected = isSelect;

            }
        }
        function GetSubscribed() {
       
            var listbox = document.getElementById('<%= lbxCustomer.ClientID %>');
            var selIndex = listbox.selectedIndex;

            if (-1 == selIndex) {
                alert("Please select one of the Customers.");
                return false;
            }

            var listbox = document.getElementById('<%= d.ClientID %>');
            var allvalue = '';
            for (var count = 0; count < listbox.options.length; count++) {

                allvalue += ',' + listbox.options[count].value;

            }

            var hiddenControl = '<%= hfSub.ClientID %>';
            document.getElementById(hiddenControl).value = allvalue;
        }
</script>


 In aspx file




You will see that there is a subscribe button because after user move list items, server side code cannot detect the items moved. So I put hidden fields and populate it in OnClientClick.
Then you need to values from Hidden field.
That's it.
Enjoy programming.

Thursday, July 4, 2013

Disable button and show loading message while user clicked in asp.net c# NOT USING UpdatePanel

 HTML
<form id="form1" runat="server"> 
        <asp:Button ID="Button1" runat="server" Text="Button" />

</form>

Codebehind
protected void Page_Load(object sender, System.EventArgs e) 
{
        Button1.Attributes.Add("onclick", (ClientScript.GetPostBackEventReference(Button1, "") + ";this.value=\'Loading...\';this.disabled = true;"));

}

class Default_ : System.Web.UI.Page 
{

protected void Button1_Click(object sender, System.EventArgs e) 

{
        System.Threading.Thread.Sleep(555);

          //Some additional logic here
          ** Without Masterpage **
        ClientScript.RegisterClientScriptBlock( this.GetType(), "reset", 

          ("document.getElementById(\'" + (Button1.ClientID + "\').disabled=false;")), true);

          ** With Masterpage **
        ScriptManager.RegisterClientScriptBlock(
this,true.GetType(), "reset", 
         ("document.getElementById(\'" + (Button1.ClientID + "\').disabled=false;")), true);
}


}

NOTE : This will not work if you are using UpdatePanel. If you are using UpdatePanel, see here.
Ref

Wednesday, July 3, 2013

Rendering ContentPlaceHolder control inside MasterPage in Windows Server 2012 and IIS 8

Today, I would like to share you all something that I found while I was trying to deploy my website to Windows Server 2012 and IIS 8.

Generally, we've already known that inside master page, the control of contentplaceholder will be generated as ctl00_ContentPlaceHolder1_ButtonID

But in IIS8, it will be generated as ContentPlaceHolder1_ButtonID

NOTE : The safer way to get the client id is <%= ButtonID.ClientID %>

More about Client ID
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
http://msdn.microsoft.com/en-us/library/1d04y8ss.aspx
http://www.dotnetcurry.com/ShowArticle.aspx?ID=273

Monday, May 20, 2013

Limit maximum characters in textbox (textarea) and display remaining count using javascript in C# Asp.Net

function Count(text, long) {
          var maxlength = new Number(long); // Change number to your max length.
          if (text.value.length > maxlength) {
              text.value = text.value.substring(0, maxlength);
              //alert(" Only " + long + " chars");
          }
          //Display remaining count
          //ctl00_ContentPlaceHolder1_lblCount.innerHTML = maxlength - text.value.length;
          var lblMsg = $get('<%= lblCount.ClientID %>');
          lblMsg.innerHTML = maxlength - text.value.length;
      }

<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" onKeyUp="javascript:Count(this,10);" onChange="javascript:Count(this,10);" ></asp:TextBox>
    <br />
    <asp:Label ID="lblCount" runat="server" Text="10"></asp:Label>

Writing Data in log file or text file line by line in C# Asp.Net

private void WriteTextFile()
    {
        string FileLoc = "C:\\LOGFOLDER\\TextFile.txt";

//This will  create the new file if the file is not exist.
        if (!File.Exists(FileLoc))
        {
            using (StreamWriter sw = File.CreateText(FileLoc))
            {
                sw.WriteLine("My Content Data");
            }
        }

//This will append to the existing file if the file already exist.
        else
        {
            using (StreamWriter sw = new StreamWriter(FileLoc, true))
            {
                sw.WriteLine("My Content Data");
            }
        }
    }

Tuesday, April 16, 2013

Asp.Net GridView useful tips and tricks

Asp.Net GridView useful tips and tricks

OUTSIDE GRIDVIEW CODE BEHIND

//Filtering only just DataRow inside GridView RowDataBound (i.e. Excluding Header, Footer and Pager)
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Finding Control inside the GridViewRow
 Button b = ((Button)e.Row.FindControl("MyButtonID"));

//Get Data Item field (Might need to validate as your own)
string CustomerID = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "CustomerID"));


//Get GridViewRow in the button click of GridView ItemTemplate
Method 1) GridViewRow gvr = (GridViewRow)(sender as Button).NamingContainer;
Method 2) GridViewRow gvr = (sender as Button).Parent.Parent as GridViewRow;

//Get Parent's GridViewRow in the button click of Nested GridView ItemTemplate
GridViewRow ParentRow = e.Row.Parent.Parent.Parent.Parent as GridViewRow;

INSIDE GRIDVIEW

//Add auto increase Sr. No. (1,2,3,4.....)
<%#Container.DataItemIndex+1 %>

//Binding Data Item
Text='<%#Eval("CustomerID")%>'

//Binding Multiple Data Items
Text='<%#Eval("Key")+"|"+Eval("Line_No") %>'

//Binding Data Item with Custom Text

Text='<%#"Customer ID is " + Eval("CustomerID")%>'

//Add Codebehind Class property inside the GridView
<%# CodeBehindProperty %>

//Adding HyperLinkField

<asp:HyperLinkField HeaderText="Customer ID" DataTextField="CustomerID" DataNavigateUrlFormatString="CustomerDetail.aspx?c=y&amp;id={0}&amp;name={1}" DataNavigateUrlFields="CustomerID,CustomerName" ControlStyle-CssClass="blulink">

 //Adding HyperLink Control in ItemTemplate
<asp:HyperLink ID="HyperLink1" runat="server"  navigateurl='<%# String.Format("~/GLEntryDetails.aspx?uid={0}&section={1}&des={2}&Field4=something", Eval("UserID"), Eval("Section"), Eval("Description")) %>' Text='<%#Eval("Click Here") %>'></asp:HyperLink>

//BoundField Data Format of Date

<asp:BoundField DataFormatString="{0:dd/MM/yyyy}" />

//Item Template Data Format of Date
<asp:ItemTemplate><asp:Label Text='<%# Bind("Expiry_Date","{0:dd-MM-yyyy}") %>'/></asp:ItemTemplate>

//BoundField Data Format of Currency
Method 1) DataFormatString="{0:#,###.00}"
Method 2) DataFormatString="{0:N2}"
Method 3) DataFormatString="{0:dd/MM/yyyy hh:mm:ss tt}"

Maintaining Cookies Variable in DLL in Asp.Net

I have mentioned about Maintaining Session Variable in DLL in Asp.net in this blog before and this is something similar to that session post.
Let me have a brief explanation of this post.
As we know, we usually see a check box saying remember me or keep logged in most of the web sites log in page.
Thus, we have to play cookie in user's browser with these functions Read, Write, Clear cookies.
Imagine how messy if we create/write/clear cookie inside the code in every time of creating/writing/clearing cookies.
In such case, how if we create CookieHelper class having Read/Write/Clearing only one time.
The example mechanism code snippet of keep me logged in is as below.

namespace MyCookieHouse
{
    public enum COOKIE_NAME
    {
        CK_KEEPLOGIN, // login
        USERINFO_USERID
    }

    [Serializable()]
    public class MyCookieHelper
    {
        public static string USER_ID //login user id OR Shipping Agent Code
        {
            get
            {
                return GetCookieValue(COOKIE_NAME.CK_KEEPLOGIN, COOKIE_NAME.USERINFO_USERID);
            }
            set
            {
                SetCookieValue(COOKIE_NAME.CK_KEEPLOGIN, COOKIE_NAME.USERINFO_USERID, value);
            }
        }
  
        public CurrentCOOKIE()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static bool IsKeepLogin()
        {
            HttpCookie ck = System.Web.HttpContext.Current.Request.Cookies[COOKIE_NAME.CK_KEEPLOGIN.ToString()];
            if (ck != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static void ClearCookie(string CookieName)
        {
            HttpCookie ck = System.Web.HttpContext.Current.Request.Cookies[CookieName];
            if (ck != null)
            {
                ck.Expires = DateTime.Now.AddDays(-1d);
                System.Web.HttpContext.Current.Response.Cookies.Add(ck);
            }
        }

        private static string GetCookieValue(COOKIE_NAME CK_NAME, COOKIE_NAME CK_NAME_KEY)
        {
            HttpCookie ck = System.Web.HttpContext.Current.Request.Cookies[CK_NAME.ToString()];
            if (ck != null)
            {
                return ck[CK_NAME_KEY.ToString()];
            }
            else
            {
                return null;
            }
        }

        private static void SetCookieValue(COOKIE_NAME CK_NAME, COOKIE_NAME CK_NAME_KEY, string COOKIEVALUE)
        {
            HttpCookie ck = System.Web.HttpContext.Current.Request.Cookies[CK_NAME.ToString()];
            if (ck != null)
            {
                ck[CK_NAME_KEY.ToString()] = COOKIEVALUE;
                System.Web.HttpContext.Current.Response.Cookies.Add(ck);
            }
            else
            {
                ck = new HttpCookie(CK_NAME.ToString());
                ck[CK_NAME_KEY.ToString()] = COOKIEVALUE;
                ck.Expires = DateTime.Now.AddYears(5);
                System.Web.HttpContext.Current.Response.Cookies.Add(ck);
            }
        }

    }
}

This is something about sharing knowledge and appreciate your comment if you have some better way.
Million thanks. Enjoy! :)

Monday, February 25, 2013

Select or Deselect all by checkbox in Gridview

By JQuery

<script type="text/javascript">
$(document).ready(function() {

var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');

headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});

});
</script>
Go to complete example


By classic javascript 

<script type="text/javascript">
function CheckAllRow(chkBox) {
var gridViewCtlId = '<%=GridView1.ClientID%>';
var grid = document.getElementById(gridViewCtlId);
var gridLength = grid.rows.length;
for (var i = 1; i < gridLength; i++) {
cell = grid.rows[i].cells[1];
for (var j = 0; j < cell.childNodes.length; j++) {
if (cell.childNodes[j].type == 'checkbox') {
cell.childNodes[j].checked = chkBox;
}
}
}
}
</script>
Go to complete example

Calling Web Services from Javascript

This also quite straight simple and I am using Asp.Net. The requirement and the procedures are as stated below.
It might be helpful if compare with Calling Code behind Server function from Javascript.

1. Using Ajax.
2. Add ScriptManager or ToolkitScriptManager
3. And a new Web Services Assuming that returning List<string>.
public class MyWebService : System.Web.Services.WebService
{
[WebMethod]
    public List<string> GetData(string CatID)
    {
        List<string> list = new List<string>();
        if (CatID== "1")
        {
            list.Add("Nokia N95");
            list.Add("Nokia N70");
            list.Add("Nokia 6630");
        }
        else
        {
            list.Add("Dell Laptop");
            list.Add("HP Laptop");
            list.Add("Sony Laptop");
        }
        return list;
    }
}
4. Add javascript function as following.
<script type="text/javascript">
       function CallWS_onclick() {
         var catid = $get('<%= txtCatID.ClientID %>').value;
         MyWebService.GetData(catid , onSuccess, onFailed);
      }
      function onSuccess(result)
      {
          var Result= $get('<%= lblResult.ClientID %>');             
         Result.innerHTML = "";
            
         for(i=0 ; i<result.length ; i++)
         {
            Result.innerHTML += result[i] + "<br />";
         }
      }
      function onFailed(error)
      {
          var Result= $get('<%= lblResult.ClientID %>');
         Result.innerHTML = "Service Error: " + error.get_message();
      }
   </script>
5. Add one input button in design page.
<input id="Button1" type="button" value="Get Products"
      onclick="Button1_onclick(this)" /> 

That's it.
Enjoy Programming ! 
Ref:http://www.ezzylearning.com/tutorial.aspx?tid=3967791&q=calling-web-services-in-client-script-using-asp-net-ajax

Sunday, February 24, 2013

Calling Code behind Server function from Javascript

It is quite straight simple and I am using Asp.Net. The requirement and the procedures are as following.
It might be helpful if compare with Calling Web Services from Javascript .
1. Using Ajax
2. Set EnablePageMethods="true" in ScriptManager or ToolkitScriptManager attribute.
3. Code behind method must be public.
4. Apply WebMethod attribute to the codebehind function [System.Web.Services.WebMethod]
[System.Web.Services.WebMethod]

public static string GetContactName(string custid)

{
   //Do Logic staff here
   return "Result";
}
5. Create javascript function
(If javascript is external file, add ref in body tag. Not in head tag.)

function CallMe(custidTextBox,DestTextBox)
 {    
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, DestTextBox);
 }
 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {    
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
6. Attach this javascript to desired control.
<input id="BtnSave" class="button_sub" name='<%# Eval("Document_No") + "|"+ Eval("Line_No")%>' type="button" value="Save" onclick="SaveByMe(this,this)" /> 
That's it.
Enjoy Programming.  
Ref : http://www.dotnetcurry.com/ShowArticle.aspx?ID=109

Tuesday, February 5, 2013

Gridview Row Mouseover highlight and anchor link


 protected void Gridview_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblDreceive = ((Label)e.Row.FindControl("lblDateReceive"));
            Label lblDissue = ((Label)e.Row.FindControl("lblDateIssue"));

            object d1 = DataBinder.Eval(e.Row.DataItem, "Posted_Purch_Receipt_Date");
            object d2 = DataBinder.Eval(e.Row.DataItem, "Sales_Shipment_Date");
            if (d1 != null)
            {
                DateTime dReceive = DateTime.Parse(d1.ToString());
                lblDreceive.Text = dReceive.Year > 1999 ? dReceive.Day.ToString("00") + "-" + dReceive.Month.ToString("00") + "-" + dReceive.Year.ToString("00") : "";
            }
            else
            {
                lblDreceive.Text = "";
            }

            if (d2 != null)
            {
                DateTime dIssue = DateTime.Parse(d2.ToString());
                lblDissue.Text = dIssue.Year > 1999 ? dIssue.Day.ToString("00") + "-" + dIssue.Month.ToString("00") + "-" + dIssue.Year.ToString("00") : "";
            }
            else
            {
                lblDissue.Text = "";
            }

            string script = String.Format("window.open('./EditBufferExchange.aspx?t=tool&entryno={0}&purrec={1}','_self')", DataBinder.Eval(e.Row.DataItem, "Entry_No"), DataBinder.Eval(e.Row.DataItem, "Posted_Purch_Receipt_No"));
            e.Row.Attributes.Add("onclick", script);

            if (e.Row.RowState == DataControlRowState.Alternate)
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#F9E5B6';this.style.cursor='pointer';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';");
            }
            else
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#F9E5B6';this.style.cursor='pointer';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#f1f3f6';");
            }


        }
    }

Thursday, January 3, 2013

SQL Helper Class

Highlight Gridview Row on Mouse Over with Navigate Link

protected void gvShowlist_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           // Navigate Link 
           string script = String.Format("window.open('./Destination.aspx?t=tool&qs1={0}&qs2={1}','_self')", DataBinder.Eval(e.Row.DataItem, "QS1_Value"), DataBinder.Eval(e.Row.DataItem, "QS2_Value"));
            e.Row.Attributes.Add("onclick", script);

           // Highlight on Mouse Over
            if (e.Row.RowState == DataControlRowState.Alternate)
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#F9E5B6';this.style.cursor='pointer';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';");
            }
            else
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#F9E5B6';this.style.cursor='pointer';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#f1f3f6';");
            }
        }
    }

Another Way with JQuery

Javascript centered popup window

function popup(url) {
        var width = screen.width - 200;
        var height = screen.height - 150;
        var left = 100;
        var top = 50;
        var params = 'width=' + width + ', height=' + height;
        params += ', top=' + top + ', left=' + left;
        params += ', directories=no';
        params += ', location=no';
        params += ', menubar=no';
        params += ', resizable=no';
        params += ', scrollbars=yes';
        params += ', status=no';
        params += ', toolbar=no';
        newwin = window.open(url, 'NewWindowPopup', params);
        if (window.focus) { newwin.focus() }
        return false;
    }

Call this Function in Code behind
ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>popup('" + url + "')</script>");

Call this Function in Code behind using Ajax WITH UpdatePanel
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenWin", "popup('" + url + "')", true);