Wednesday, 27 November 2013

Bind Comma Separated string Values into Dropdown

 string str = "A,B,C,D,";
            //Declare a arraylist for getting comma separated string
            ArrayList arr = new ArrayList();
            //check wether the re is comma in the end of the string
            if (str.Trim().EndsWith(","))
            {
                str = str.Substring(0, str.Length - 1);
            }
            //split the comma separated string into arraylist
            arr.AddRange(str.Split(','));
            //loop through the arraylist items & add the item to Dropdownlist
            for (int i = 0; i < arr.Count; i++)
            {
                DropDownList1.Items.Insert(i, new ListItem(arr[i].ToString(), (i + 1).ToString()));
            }

Sunday, 24 November 2013

by entering percentage on textbox it will calculate grid column percentage and add that percentage amount with that column amount and stored it to another column for every line item of the grid

function fcnDistribution() {
     // ClearValues();
     var gridrowLength = $("span[id$=lblSCAmount]").length;
     var Percentage = $("[id$='txtServiceChargePerc']").val();
     // alert("Percentage" + Percentage);
     $("span[id$=lblSCAmount]").each(function () {
         var id = $(this).attr('id');
         var rowId = id.substr(id.length - 17).substr(0, 5);
         var ScAmount = Filtervalue($(this));
         // alert("SC Amount" + ScAmount);
         // alert(parseFloat(ScAmount) +"\r\n"+ parseFloat(Percentage.replace("%", '')))
         //if()
         {

             var perCAmount = parseFloat((parseFloat(ScAmount) * parseFloat(Percentage.replace("%", ''))) / 100);
             // alert("perCAmount" + perCAmount);
             var totalamt = parseFloat(perCAmount) + parseFloat(ScAmount);
             //alert("total" + totalamt);
         }
         var txtChargeAmountId = $("[id$=" + rowId + "_txtChargeAmount]");
         //alert("txtAmountId" + txtChargeAmountId.val());
         var ChargeAmt = "$" + parseFloat(totalamt, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
         txtChargeAmountId.val(ChargeAmt);
     });
 }


   function ValidatePercent() {

        var ServiceChargePerc = $("[id$='txtServiceChargePerc']");

        $(ServiceChargePerc).keydown(function (event) {
           // onlyNumbers(event);

            $(ServiceChargePerc).focusout(function (event) {
                var percent = $(ServiceChargePerc).val().replace("$", " ");

                if (percent.indexOf('%') == -1 && $(ServiceChargePerc).val().length != 0)
                    $(ServiceChargePerc).val(parseFloat(percent).toFixed(2) + "%");

            });
        });




 function Filtervalue(input) {
     var Output = input.text();
     // alert(1);
     Output = Output.replace("$", ''); //Replace  "$"(Doller) with empty string    
     Output = Output.replace(/,/g, '');   //Replace n no of ","(camas) with empty string
     return Output;
 }


------------ textbox focus out event call function
function MouseOutvalidationReceiptHeader() {

     var txtAmountReceipt = $("[id$='txtServiceChargePerc']");


     txtAmountReceipt.focusout(function () {
         if ($.trim(txtAmountReceipt.val()) != "") {
              fcnDistribution();
             ValidatePercent();
         }
     });
 }

----------call method on postback and ready

 $(document).ready(function () {
        ValidatePercent();
        WOChargesFocusOutValid();
        MouseOutvalidationReceiptHeader();
 
    });

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(function (s, e) {
        ValidatePercent();
        MouseOutvalidationReceiptHeader();
        $('form').dirtyForms();

    });

Jquery for Grid textbox validation with required field


    function ValidateElement(element) {

        if ($(element).val() == '') {
            $(element).css("border", "1px solid red");
        }

        $(element).hover(function () {
            if ($(element).val() == '') {
           
                qtipPopup(element, "Required Field");
            }
        },
          function () {
              if ($(element).data("qtip")) $(element).qtip("destroy");
          });

        $(element).focusout(function () {
            if ($(element).val() != '') {
                $(element).css("border", "");
            }
            else {
                $(element).css("border", "1px solid red");
            }
        });

    }

    function qtipPopup(element, message) {
        $.fn.qtip.zindex = "999";
        if ($(element).data("qtip")) $(element).qtip("destroy");
        $(element).css("border", "1px solid red");
        $(element).qtip({
            overwrite: false, content: message,
            position: { my: 'bottomLeft', at: 'leftTop' },
            show: { event: 'focus' },
            hide: { event: 'focusout' },
            style: { classes: 'ui-tooltip-green', name: 'dark' }
        });
    }

    function GridTextValidation() {

        var gridValid = true;
        var loopStart = ($("[id$='grdWorkOrderCharges']").find('tr').length > 9) ? 0 : 1;
        for (var i = loopStart; i < $("[id$='grdWorkOrderCharges']").find('tr').length; i++) {

            var rowData1 = $("[id$='grdWorkOrderCharges']").find('tr')[i];

            var ChargeAccountInfo = $(rowData1).find('input[id$=txtChargeAccount]');

            if ($(ChargeAccountInfo) != null) {

                if ($(ChargeAccountInfo).val().length > 0) {
                    if ($(ChargeAccountInfo).data("qtip"))
                        $(ChargeAccountInfo).qtip("destroy");
                }
                else {
                    ValidateElement($(ChargeAccountInfo));
                    gridValid = false;

                }
            }

        }
        return gridValid;
    }

Grid total column values calculate and display into the label

   function AddTotal() {
        var tot = 0.00;
        $("[id$='txtChargeAmount']").each(function () {
            var sum = $(this).val();
            // alert('sum' + sum);
            sum = sum.replace("$", ''); //Replace  "$"(Doller) with empty string    
            sum = sum.replace(/,/g, '');   //Replace n no of ","(camas) with empty string    

            if (isNaN(sum)) {
                //alert(sum + ' is not a number');
            }
            else {
                if (sum == "") {
                    sum = 0;
                }
                tot += parseFloat(sum);
            }
        });
        //Display the total sum of Values to "txtAmountReceipt" control
        var Total = '$' + tot.toFixed(2);
        $("[id$='lblTotalAmount']").text(Total);
        // $("[id$='hdnTotalAmount']").val(Total);
    }

Tuesday, 29 October 2013

grid having button click event code behind retrive grid selected checkbox values



            string ids = string.Empty;
            ids = (from GridViewRow gvSingleSavingsBookRow in grvVendorProperties.Rows
                   let rowSelected = (CheckBox)gvSingleSavingsBookRow.FindControl("chkVendorProperties")
                   let myId = (HiddenField)gvSingleSavingsBookRow.FindControl("HiddenEntityID")
                   where (null != rowSelected) && (null != myId)
                         && rowSelected.Checked
                   select myId).Aggregate(ids, (current, myId) =>
                                string.Format("{0}{1}{2}", current, myId.Value.Trim(), ","));



-----------------------------------------------------------------------------

for (int rowIndex = 0; rowIndex < grvVendorProperties.Rows.Count; rowIndex++)
            {
                TextBox txtExpenseAccount = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtExpenseAccount");
                TextBox txtInitialBalance = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtInitialBalance");
                Button btnExpenseAccount = (Button)grvVendorProperties.Rows[rowIndex].FindControl("btnExpenseAccount");
                TextBox txtEffectiveDate = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtEffectiveDate");
                TextBox txtReceiptAccount = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtReceiptAccount");
                Button btnReceiptAccount = (Button)grvVendorProperties.Rows[rowIndex].FindControl("btnReceiptAccount");

                CheckBox chk = (CheckBox)grvVendorProperties.Rows[rowIndex].FindControl("chkVendorProperties");

                if (chk.Checked == true)
                {
                    chk.Checked = true;
                    txtExpenseAccount.Enabled = true;
                    txtInitialBalance.Enabled = true;
                    btnExpenseAccount.Enabled = true;
                    txtEffectiveDate.Enabled = true;
                    txtReceiptAccount.Enabled = true;
                    btnReceiptAccount.Enabled = true;
                }
                else
                    chk.Checked = false;
            }

grid row having button and after click particulare row button event find entire grid checkbox selected rows only using linq list

     
  List<int> listIndex = CheckedRows.AsEnumerable().Select(f => f.RowIndex).ToList();

            foreach (int rowIndex in listIndex)
            {
                TextBox txtExpenseAccount = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtExpenseAccount");
                TextBox txtInitialBalance = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtInitialBalance");
                Button btnExpenseAccount = (Button)grvVendorProperties.Rows[rowIndex].FindControl("btnExpenseAccount");
                TextBox txtEffectiveDate = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtEffectiveDate");
                TextBox txtReceiptAccount = (TextBox)grvVendorProperties.Rows[rowIndex].FindControl("txtReceiptAccount");
                Button btnReceiptAccount = (Button)grvVendorProperties.Rows[rowIndex].FindControl("btnReceiptAccount");

                txtExpenseAccount.Enabled = true;
                txtInitialBalance.Enabled = true;
                btnExpenseAccount.Enabled = true;
                txtEffectiveDate.Enabled = true;
                txtReceiptAccount.Enabled = true;
                btnReceiptAccount.Enabled = true;

            }




Monday, 28 October 2013

Grid view button click dont want to referesh grid

 <asp:UpdatePanel ID="UpdatePanel1" runat="server" >
            <ContentTemplate>
  <asp:Button ID="btnExpenseAccount" runat="server" CssClass="button_small_tgrid" Text="..."
                                                    Enabled="false" OnClick="btnExpenseAccount_Click" />
 </ContentTemplate>
 </asp:UpdatePanel>

protected void btnExpenseAccount_Click(object sender, EventArgs e)
        {
Button btn = (Button)sender;
UpdatePanel1.Triggers.Add(new AsyncPostBackTrigger { ControlID = btn.UniqueID, EventName = "click" });
}

Friday, 25 October 2013

when mouse over to the link it will show pointer

 <asp:Label ID="lnkSelectAll"  runat="server" Text="Select All" Style="cursor: pointer" >
</asp:Label>

Gridview column bind with substring and ... if exceed column width limit and showing tooltip with entirecolumn text

 <asp:Label ID="lblProperty" runat="server" Text='<%# Eval("PropertyName").ToString().Length <= 15 ?                Eval("PropertyName") : Eval("PropertyName").ToString().Substring(0,15)+"..." %>'
             ToolTip='<%# Eval("PropertyName") %>' Visible="true"></asp:Label>



we also can do this substring column by using row data bound event below code explain how we can do this

  protected void grvVendorProperties_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {

     Label lblName = (Label)e.Row.FindControl("lblProperty");
                string strName = lblName.Text;
                if (strName.Length > 7)
                {
                    lblName.Text = strName.Substring(0, 7) + "..";
                    lblName.ToolTip = strName;
                }
}
}

Grid view check box all script

 //********************Check box all script*******************************
    function GetChecked() {
        var grdView = $('#<%= grvVendorProperties.ClientID %>');
        var tr = $('#<%= grvVendorProperties.ClientID %>').find('tr');
        $('#<%= grvVendorProperties.ClientID %>').find('tr').find('input:checkbox[name$=chkVendorProperties]').each(function () {
            if (this.checked) {
                $(this).parents('tr').find('[id$=txtEffectiveDate]').datepicker('enable');
                $(this).parents('tr').find('[id$=btnExpenseAccount]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtExpenseAccount]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtInitialBalance]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtEffectiveDate]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtReceiptAccount]').attr("disabled", "");
                $(this).parents('tr').find('[id$=btnReceiptAccount]').attr("disabled", "");
            }
            else {
                $(this).parents('tr').find('[id$=txtEffectiveDate]').datepicker('disable');
                $(this).parents('tr').find('[id$=btnExpenseAccount]').attr("disabled", "disabled");
                $(this).parents('tr').find('[id$=txtExpenseAccount]').attr('disable', 'disabled');
                $(this).parents('tr').find('[id$=txtInitialBalance]').attr("disable", "disabled");
                $(this).parents('tr').find('[id$=txtEffectiveDate]').attr("disable", "disabled");
                $(this).parents('tr').find('[id$=txtReceiptAccount]').attr("disable", "disabled");
                $(this).parents('tr').find('[id$=btnReceiptAccount]').attr("disable", "disabled");

            }

        });
    }


    function GetCheckStatus() {
        var srcControlId = event.srcElement.id;
        var txtEffectiveDate = event.srcElement.id.replace('chkVendorProperties', 'txtEffectiveDate');
        var txtInitialBalance = event.srcElement.id.replace('chkVendorProperties', 'txtInitialBalance');
        var txtExpenseAccount = event.srcElement.id.replace('chkVendorProperties', 'txtExpenseAccount');
        var txtReceiptAccount = event.srcElement.id.replace('chkVendorProperties', 'txtReceiptAccount');
        var btnExpenseAccount = event.srcElement.id.replace('chkVendorProperties', 'btnExpenseAccount');
        var btnReceiptAccount = event.srcElement.id.replace('chkVendorProperties', 'btnReceiptAccount');
        if (document.getElementById(srcControlId).checked) {
            //   $('#ctl00_ctl00_plcHolderHomemaster_plcHolderSubModuleData_VendorProperty_grvVendorProperties_ctl05_txtEffectiveDate').datepicker('enable');
            //  $(txtEffectiveDate).datepicker('enable');
            //$("[id$='txtEffectiveDate']").datepicker("enable");

            document.getElementById(txtEffectiveDate).disabled = false;
            document.getElementById(txtInitialBalance).disabled = false;
            document.getElementById(txtExpenseAccount).disabled = false;
            document.getElementById(txtReceiptAccount).disabled = false;
            document.getElementById(btnExpenseAccount).disabled = false;
            document.getElementById(btnReceiptAccount).disabled = false;


        }
        else {
            /// $('#ctl00_ctl00_plcHolderHomemaster_plcHolderSubModuleData_VendorProperty_grvVendorProperties_ctl05_txtEffectiveDate').datepicker('disable');
            //$(txtEffectiveDate).datepicker('disable');
            document.getElementById(txtEffectiveDate).disabled = true;
            document.getElementById(txtInitialBalance).disabled = true;
            document.getElementById(txtExpenseAccount).disabled = true;
            document.getElementById(txtReceiptAccount).disabled = true;
            document.getElementById(btnExpenseAccount).disabled = true;
            document.getElementById(btnReceiptAccount).disabled = true;
        }
    }


    function selectAll(checked) {

        var txtExpenseAccount = $("[id$='txtExpenseAccount']");
        var btnExpenseAccount = $("[id$='btnExpenseAccount']");
        var txtInitialBalance = $("[id$='txtInitialBalance']");
        var txtEffectiveDate = $("[id$='txtEffectiveDate']");
        var txtReceiptAccount = $("[id$='txtReceiptAccount']");
        var btnReceiptAccount = $("[id$='btnReceiptAccount']");
        $("[id$='txtEffectiveDate']").datepicker("enable");

        if (checked) {
            $('input:checkbox[name$=chkVendorProperties]').each(function () {
                txtExpenseAccount.removeAttr("disabled");
                btnExpenseAccount.removeAttr("disabled");
                txtInitialBalance.removeAttr("disabled");
                txtEffectiveDate.removeAttr("disabled");
                txtReceiptAccount.removeAttr("disabled");
                btnReceiptAccount.removeAttr("disabled");
                $(this).attr('checked', 'checked');
            });
        }
    }


    function UnselectAll(checked) {
        var txtExpenseAccount = $("[id$='txtExpenseAccount']");
        var btnExpenseAccount = $("[id$='btnExpenseAccount']");
        var txtInitialBalance = $("[id$='txtInitialBalance']");
        var txtEffectiveDate = $("[id$='txtEffectiveDate']");
        var txtReceiptAccount = $("[id$='txtReceiptAccount']");
        var btnReceiptAccount = $("[id$='btnReceiptAccount']");
        $("[id$='txtEffectiveDate']").datepicker("disable");
        if (checked) {
            $('input:checkbox[name$=chkVendorProperties]').each(
                    function () {

                        txtExpenseAccount.attr("disabled", "disabled");
                        btnExpenseAccount.attr("disabled", "disabled");
                        txtInitialBalance.attr("disabled", "disabled");
                        txtEffectiveDate.attr("disabled", "disabled");
                        txtReceiptAccount.attr("disabled", "disabled");
                        btnReceiptAccount.attr("disabled", "disabled");
                        $(this).removeAttr('checked');
                    });
        }
    }
    //********************Check box all script*******************************

grid view row button click enable disable entire grid textbox,buttons if checkbox checked or unchecked

 
        protected void btnExpenseAccount_Click(object sender, EventArgs e)
        {
 ScriptManager.RegisterStartupScript(this, GetType(), "key1", string.Format("GetChecked();"), true);
}


----------------------------------------------------------------------------


<script type="text/javascript">
 function GetChecked() {
            var grdView = $('#<%= grvVendorProperties.ClientID %>');
        var tr = $('#<%= grvVendorProperties.ClientID %>').find('tr');
        $('#<%= grvVendorProperties.ClientID %>').find('tr').find('input:checkbox[name$=chkVendorProperties]').each(function () {
            if (this.checked) {
                $(this).parents('tr').find('[id$=txtEffectiveDate]').datepicker('enable');
                $(this).parents('tr').find('[id$=btnExpenseAccount]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtExpenseAccount]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtInitialBalance]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtEffectiveDate]').attr("disabled", "");
                $(this).parents('tr').find('[id$=txtReceiptAccount]').attr("disabled", "");
                $(this).parents('tr').find('[id$=btnReceiptAccount]').attr("disabled", "");
            }
            else {
                $(this).parents('tr').find('[id$=txtEffectiveDate]').datepicker('disable');
                $(this).parents('tr').find('[id$=btnExpenseAccount]').attr("disabled", "disabled");
                $(this).parents('tr').find('[id$=txtExpenseAccount]').attr('disable', 'disabled');
                $(this).parents('tr').find('[id$=txtInitialBalance]').attr("disable", "disabled");
                $(this).parents('tr').find('[id$=txtEffectiveDate]').attr("disable", "disabled");
                $(this).parents('tr').find('[id$=txtReceiptAccount]').attr("disable", "disabled");
                $(this).parents('tr').find('[id$=btnReceiptAccount]').attr("disable", "disabled");
             
            }

        });
   }

</script>

Grid select all check box and unselect all check box

  <asp:Label ID="lnkSelectAll" runat="server" Text="Select All" CssClass="graylink_13"
onclick="selectAll(this);" ToolTip="Select All" Font-Underline="false" ClientIDMode="Static" ForeColor="Black"> </asp:Label>
<asp:Label ID="lnkUnSelectAll" runat="server" Text="Select None" CssClass="graylink_13"
  onclick="UnselectAll(this);" ToolTip="Select None" Font-Underline="false" ClientIDMode="Static" ForeColor="Black" />
---------------------------------------------------------------------------

<script type="text/javascript">

  function selectAll(checked) {
 
       var txtExpenseAccount = $("[id$='txtExpenseAccount']");
        var btnExpenseAccount = $("[id$='btnExpenseAccount']");
        var txtInitialBalance = $("[id$='txtInitialBalance']");
        var txtEffectiveDate = $("[id$='txtEffectiveDate']");
        var txtReceiptAccount = $("[id$='txtReceiptAccount']");
        var btnReceiptAccount = $("[id$='btnReceiptAccount']");
        $("[id$='txtEffectiveDate']").datepicker("enable");

        if (checked) {
            $('input:checkbox[name$=chkVendorProperties]').each(function () {
                        txtExpenseAccount.removeAttr("disabled");
                        btnExpenseAccount.removeAttr("disabled");
                        txtInitialBalance.removeAttr("disabled");
                        txtEffectiveDate.removeAttr("disabled");
                        txtReceiptAccount.removeAttr("disabled");
                        btnReceiptAccount.removeAttr("disabled");
                        $(this).attr('checked', 'checked');
                    });
        }
    }


    function UnselectAll(checked) {
        var txtExpenseAccount = $("[id$='txtExpenseAccount']");
        var btnExpenseAccount = $("[id$='btnExpenseAccount']");
        var txtInitialBalance = $("[id$='txtInitialBalance']");
        var txtEffectiveDate = $("[id$='txtEffectiveDate']");
        var txtReceiptAccount = $("[id$='txtReceiptAccount']");
        var btnReceiptAccount = $("[id$='btnReceiptAccount']");
        $("[id$='txtEffectiveDate']").datepicker("disable");
        if (checked) {
            $('input:checkbox[name$=chkVendorProperties]').each(
                    function () {
                     
                        txtExpenseAccount.attr("disabled", "disabled");
                        btnExpenseAccount.attr("disabled", "disabled");
                        txtInitialBalance.attr("disabled", "disabled");
                        txtEffectiveDate.attr("disabled", "disabled");
                        txtReceiptAccount.attr("disabled", "disabled");
                        btnReceiptAccount.attr("disabled", "disabled");
                        $(this).removeAttr('checked');
                    });
        }
    }

</script>

jquery Date picker control enable and disable call it on ready and add_endRequest function

    function datpickerenabledisable() {
        $("[id$=chkVendorProperties]").each(function () {
            $(this).click(function () {
                if (this.checked) {
                    $(this).parents('tr').find('[id$=txtEffectiveDate]').datepicker('enable');
                }
                else {
                    $(this).parents('tr').find('[id$=txtEffectiveDate]').datepicker('disable');
                }
            });
        });
    }

Gridview row having button and button click event enable disabling grid view textboxes

 protected void btnExpenseAccount_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            GridViewRow grv = (GridViewRow)btn.NamingContainer;
            int index = grv.RowIndex;
            TextBox txtExpenseAccount = (TextBox)grvVendorProperties.Rows[index].FindControl("txtExpenseAccount");
            TextBox txtInitialBalance = (TextBox)grvVendorProperties.Rows[index].FindControl("txtInitialBalance");
            Button btnExpenseAccount = (Button)grvVendorProperties.Rows[index].FindControl("btnExpenseAccount");
            TextBox txtEffectiveDate = (TextBox)grvVendorProperties.Rows[index].FindControl("txtEffectiveDate");
            TextBox txtReceiptAccount = (TextBox)grvVendorProperties.Rows[index].FindControl("txtReceiptAccount");
            Button btnReceiptAccount = (Button)grvVendorProperties.Rows[index].FindControl("btnReceiptAccount");
            txtExpenseAccount.Enabled = true;
            txtInitialBalance.Enabled = true;
            btnExpenseAccount.Enabled = true;
            txtEffectiveDate.Enabled = true;
            txtReceiptAccount.Enabled = true;
            btnReceiptAccount.Enabled = true;

 }

Thursday, 3 October 2013

MaskedEdit "backspace" and delete problem with safari and chrome -- here's the fix!

the fix is easy. in the current source code of MaskedEditBehavior.js about line 890 you have this:


if (Sys.Browser.agent == Sys.Browser.InternetExplorer || evt.type == "keypress")  
    {
        if (scanCode == 8) // BackSpace
the code should be
if (Sys.Browser.agent == Sys.Browser.InternetExplorer || evt.type == "keydown")  
    {
        if (scanCode == 8) // BackSpace
     ...

Saturday, 21 September 2013

asp.net Time textbox

 aspx page code.

<script type="text/javascript">

    // Time validation for Scheduled Time
    function ValidateScheduledTimeFormatSC() {

        var msg = "";
        var txtTimeValue = $("[id*='txtSchTime']").val();
        regularExpression = /^(\d{1,2}):(\d{2})(:00)?(\s)?([AP]M|[ap]m)?$/;
        try {
            if (txtTimeValue != '') {
                if (arrregularExpressions = txtTimeValue.match(regularExpression)) {
                    if (arrregularExpressions[4]) {
                        // check for am/pm. This is 12hours time format check
                        if (arrregularExpressions[1] < 1 || arrregularExpressions[1] > 12) {
                            msg = "Error: enter valid hours. Either 12hours with am/pm here am/pm is optional(or) 24hours time format: ";
                        }
                    }
                    else {
                        // This is 24hours time format check
                        if (arrregularExpressions[1] > 23) {
                            msg = "Error: enter valid hours. Either 12hours with am/pm (or) 24hours time format: ";
                        }
                    }
                    if (!msg && arrregularExpressions[2] > 59) {
                        msg = "Error: enter valid minutes: " + arrregularExpressions[2];
                    }
                }
                else {
                    msg = "Error: enter valid time format. Example: 10:15am or 19:20: ";
                }
            }
            else {
                $("#divSchTimeFormatError").css("display", "block");              
           
            }
            if (msg != "" && txtTimeValue != "__:__ AM" && txtTimeValue != "__:__ PM") {
                $("#divSchTimeFormatError").css("display", "block");              
               return false;
            }
            else {
                if (msg != "") {
                    $("#divSchTimeFormatError").css("display", "none");                  
                    return true;
                }
                else {
                    $("#divSchTimeFormatError").css("display", "none");                  
                    return true;
                }
            }
         
        }
        catch (ex) { alert(ex); }

    }
</script>




 <div class="fieldset" runat="server" id="divScheduledTime">
                    <label>
                        <span id="span2" runat="server">Scheduled Time </span>
                        <asp:Label ID="lblSchTime" Visible="false" runat="server"></asp:Label>
                    </label>                  
                   <div id="divSchTimeFormatError" class="tooltip" style="margin-left: 410px;">
                        <span class="pointer"></span>Scheduled Time is not valid
                    </div>          

                    <div class="margin_bottom_5">                      
                        <asp:TextBox ID="txtSchTime" runat="server" ClientIDMode="Static" class="inputTextTime"
                            onblur="ValidateScheduledTimeFormatSC();"></asp:TextBox>
                        <Ajax:MaskedEditExtender ID="MaskedSchTime" runat="server" AcceptAMPM="true" Mask="99:99"
                            AcceptNegative="None" Enabled="True" MaskType="Time" TargetControlID="txtSchTime" ClearTextOnInvalid="true"  >
                        </Ajax:MaskedEditExtender>
                    </div>
                </div>



Generic list sum Amount column value

 decimal sum = listServiceCall.Select(f => Convert.ToDecimal((f.AMOUNT.ToString().IndexOf("$") != -1) ? f.AMOUNT.Replace("$", "") : (f.AMOUNT != "") ? f.AMOUNT : "0")).Sum();

Grid view calculate amount column total to grid footer label

 Example:-1  best example working fine

  function AddTotal() {    
        var tot = 0.00;
        $("[id$='vtxtAmount']").each(function () {
            var sum = $(this).val();
           // alert('sum' + sum);
            sum = sum.replace("$", ''); //Replace  "$"(Doller) with empty string    
            sum = sum.replace(/,/g, '');   //Replace n no of ","(camas) with empty string    

            if (isNaN(sum)) {
                //alert(sum + ' is not a number');
            }
            else {
                if (sum == "") {
                    sum = 0;
                }
                tot += parseFloat(sum);
            }
        });
        //Display the total sum of Values to "txtAmountReceipt" control
        var Total = '$' + tot.toFixed(2);
        $("[id$='lblTotalAmount']").text(Total);
        $("[id$='hdnTotalAmount']").val(Total);
    }
   
------------------------------------------------------------------------
Example:2   not best example some time its not work

 function AddTotal() {
        var TotalDebit = 0;
        $("[id$='vtxtAmount']").each(function () {
            var data = $(this).val();
            if (data != "" && data.indexOf("$") !== -1) {
                data = data.substring(1);
            }
            var addValue = data;
            if (addValue != "") {
                if (isNaN(parseFloat(addValue))) {
                }
                else {
                    TotalDebit = (parseFloat(TotalDebit) + parseFloat(addValue));
                }
            }
        });
        document.getElementById('lblTotalAmount').innerHTML = "$" + parseFloat(TotalDebit).toFixed(2);
            $("[id$='hdnTotalAmount']").val(document.getElementById('lblTotalAmount').innerHTML);
    $("[id$='lblTotalAmount']").text = "$" + parseFloat(TotalDebit).toFixed(2);
    $("[id$='hdnTotalAmount']").val($("[id$='lblTotalAmount']").text);
    }
-----------------------------------------------------------------------------------------------------------------

Saturday, 20 July 2013

display all the employees whose hiredate is not the first day of the month or the last day of the month

 select empid  from emp
 where datepart(dd,GETDATE()) != 1
 and datepart(dd,getdate()) !=
  DATEADD(dd,-day(dateadd(mm,1,getdate())), dateadd(mm,1,getdate()))


 select  DATEADD(dd,-day(dateadd(mm,1,getdate())), dateadd(mm,1,getdate()))

select  dateadd(mm,1,getdate())

SQL training Procedure and views

simple view


create view Emp_view
as

select empid,ename,gender from emp

insert into Emp_view values (11,'sssss','M')


Alter view Emp_view as select empid,ename,gender,sal,deptno from emp





multitable view

create view emp_dept
as
select empid,ename,emp.deptno,dept.dname from emp,dept where emp.deptno = dept.deptno

insert into emp_dept values (111,'sdff',1,'marketing')


giving error not allowed to insert records on multiple jointable view




temporory table example procedure

Create Procedure tempororytable
@startWith nvarchar(50)
As
Begin
Declare @EMPCOUNT int
Set nocount on;
Select p.empid, p.ename
into #Temp
 from emp as p
where
p.ename like @startWith + N'%';
Select
t.ename,  COUNT(*) as EMPCOUNT from #Temp as t
group by
t.ename;

--Print EMPCOUNT
Drop table #Temp;
End
GO



Cursor Example

Create procedure CursorDemo
as
Declare @Ename varchar (20)
Declare @Ename1 Varchar(30)

Declare @getEname CURSOR

Set @getename  = CURSOR For

select ename from emp

Open @getEname

Fetch Next from @getEname into @Ename
while @@FETCH_STATUS  = 0
Begin


set @Ename1 = (@Ename + 'AAAA')
Print @Ename1
Fetch Next
From @getEname into @Ename
END
Close @getEname
Deallocate @getEname
GO

EXEC CursorDemo






Procedure @@ERROR and @@rowcount

Create Procedure GetData
(
@DEPTNo int,
@sal int
)
As
begin
Declare @ErrorVar int;
Declare @RowcountVar int;

update emp set sal= sal + 1000 where deptno = @DEPTNo

select @ErrorVar = @@ERROR,
@RowcountVar = @@ROWCOUNT;

if(@ErrorVar <> 0)
Begin
    if @ErrorVar = 547
  BEGIN
     print N'Invalid';
     return 1;
  End
Else
   Begin
   Print N'Error';
   return 2;
   End

End
Else
Begin
if @RowcountVar = 0
Begin
 print 'warning';
End
Else
Begin
print 'updated'
Return 0;
End
end
End



EXEC GetData 15,1000


Friday, 19 July 2013

Linq best example

  protected void lnkGrouptoDeposit_Click(object sender, EventArgs e)
        {

            double TotalAmount = 0.00;

            if (Request.Cookies["GeneralInfo"] != null)
            {
                HttpCookie cookie = Request.Cookies["GeneralInfo"];
                if (cookie != null)
                {
                    string strIndNew = gridAria.SelectedIndexVal.Replace("undefined", "0");
                    List<int> ListSele = (string.IsNullOrWhiteSpace(strIndNew)) ? new List<int>() : strIndNew.Split(',').Select(n => int.Parse(n)).Distinct().ToList();
                    cookie["EntityIdList"] = String.Join(",", ListSele.Select(x => x.ToString()).ToArray());
                    ViewState["EntityIdList"] = gridAria.ListChecked;
                }
                Response.Cookies.Add(cookie);
            }



            List<int> ListCheckedtest = gridAria.ListChecked;
            if (ListCheckedtest.Count > 0)
            {
                clsTransactionBO objDepositBO = new clsTransactionBO();

                int intEntityID = ListCheckedtest.FirstOrDefault();
                clsTransactionBO objTransModel = new clsTransactionBO();
                if (ViewState["ListData"] != null)
                {
                    uclCommonPopup.Visible = true;
                    NextGen.Controls.Common.clsGridBind<clsTransactionBO> objTransGridList = (NextGen.Controls.Common.clsGridBind<clsTransactionBO>)ViewState["ListData"];
                    List<clsTransactionBO> objList = objTransGridList.GridList.ToList();
                    objTransModel = objList.Where(x => x.EntityID == intEntityID).SingleOrDefault();
                }
                uclGroupReceipts.EntityList = String.Join(",", gridAria.ListChecked.Select(x => x.ToString()).ToArray());

                if (objTransModel != null && objTransModel.TransTypeId == 1)
                {

                    listGroupReceiptXML = GetReceiptList();
                    // we get selected list
                    int bankkid = listGroupReceiptXML.Select(b => b.BankAccountID).FirstOrDefault();
                    int countBankAccountID = listGroupReceiptXML.Count(b => b.BankAccountID == bankkid);
                    if (countBankAccountID == listGroupReceiptXML.Count)
                    {
                        int countDepositID = listGroupReceiptXML.Count(b => b.DepositID > 0);
                        if (countDepositID > 0)
                        {
                            uclCommonPopup.Alert("Display Message Box", "One or more Receipts have already been grouped to a deposit");
                        }
                        else
                        {
                            for (int i = 0; i < listGroupReceiptXML.Count; i++)
                            {
                                TotalAmount += Convert.ToDouble(listGroupReceiptXML[i].Amount);
                            }
                            objDepositBO.EntityIdList = XMLConvert(uclGroupReceipts.EntityList);
                            objDepositBO.Amount = TotalAmount.ToString();
                            objDepositBO.NoOfItems = Convert.ToString(ListCheckedtest.Count);
                            uclGroupReceipts.GroupDepositModel = objDepositBO;
                            uclGroupReceipts.ControlStatus = true;
                            mdlGrouptoDeposit.Show();
                        }

                    }
                    else
                    {
                        uclCommonPopup.Alert("Display Message Box", "Please select same bank account");
                    }

                }
                else
                {
                    uclCommonPopup.Alert("Display Message Box", "Selected items must be receipts");
                }
            }
            else
            {
                uclCommonPopup.Alert("Display Message Box", "At least one receipt must be selected before proceeding");
            }

            //CreateCookie();

        }

Asp .net list for loop best example


        protected void lnkGrouptoDeposit_Click(object sender, EventArgs e)
        {
         
            double TotalAmount = 0.00;
            //gridAria.SortCheckBoxList();
         
            if (Request.Cookies["GeneralInfo"] != null)
            {
                HttpCookie cookie = Request.Cookies["GeneralInfo"];
                if (cookie != null)
                {
                    string strIndNew = gridAria.SelectedIndexVal.Replace("undefined", "0");
                    List<int> ListSele = (string.IsNullOrWhiteSpace(strIndNew)) ? new List<int>() : strIndNew.Split(',').Select(n => int.Parse(n)).Distinct().ToList();
                    cookie["EntityIdList"] = String.Join(",", ListSele.Select(x => x.ToString()).ToArray());
                    ViewState["EntityIdList"] = gridAria.ListChecked;
                }
                Response.Cookies.Add(cookie);
            }
            //VerifyCookie();
            //List<int> ListCheckedtest = (ViewState["EntityIdList"] != null || Convert.ToString(ViewState["EntityIdList"]) != "") ? (List<int>)ViewState["EntityIdList"] : new List<int>();



            List<int> ListCheckedtest = gridAria.ListChecked;
            if (ListCheckedtest.Count > 0)
            {
                clsTransactionBO objDepositBO = new clsTransactionBO();

                int intEntityID = ListCheckedtest.FirstOrDefault();
                clsTransactionBO objTransModel = new clsTransactionBO();
                if (ViewState["ListData"] != null)
                {
                    uclCommonPopup.Visible = true;
                    NextGen.Controls.Common.clsGridBind<clsTransactionBO> objTransGridList = (NextGen.Controls.Common.clsGridBind<clsTransactionBO>)ViewState["ListData"];
                    List<clsTransactionBO> objList = objTransGridList.GridList.ToList();
                    objTransModel = objList.Where(x => x.EntityID == intEntityID).SingleOrDefault();
                }
                uclGroupReceipts.EntityList = String.Join(",", gridAria.ListChecked.Select(x => x.ToString()).ToArray());

                if (objTransModel != null && objTransModel.TransTypeId == 1)
                {

                    listGroupReceiptXML = GetReceiptList();
                    bool flag = false;


                    if (ListCheckedtest.Count == 1)
                    {
                        flag = false;
                    }
                    else
                    {
                        for (int i = 0; i < listGroupReceiptXML.Count; i++)
                        {
                            for (int j = 0; j < listGroupReceiptXML.Count; j++)
                            {
                                if (i != j)
                                {
                                    if (Convert.ToDouble(listGroupReceiptXML[i].BankAccountID) != Convert.ToDouble(listGroupReceiptXML[j].BankAccountID))
                                    {
                                        flag = true;
                                        break;
                                    }

                                }

                            }
                            if (flag == true)
                                break;
                        }

                    }
                    if (flag != true)
                    {
                        bool boolDepositalreadyexist = false;
                        for (int i = 0; i < listGroupReceiptXML.Count; i++)
                        {
                            if ( Convert.ToInt32(listGroupReceiptXML[i].DepositID) != 0)
                            {
                                uclCommonPopup.Alert("Display Message Box", "One or more Receipts have already been grouped to a deposit");
                                boolDepositalreadyexist = true;
                                break;
                            }
                        }
                        if (boolDepositalreadyexist != true)
                        {
                            for (int i = 0; i < listGroupReceiptXML.Count; i++)
                            {
                                TotalAmount += Convert.ToDouble(listGroupReceiptXML[i].Amount);
                            }

                            objDepositBO.EntityIdList = XMLConvert(uclGroupReceipts.EntityList);
                            objDepositBO.Amount = TotalAmount.ToString();
                            objDepositBO.NoOfItems = Convert.ToString(ListCheckedtest.Count);
                            uclGroupReceipts.GroupDepositModel = objDepositBO;
                            uclGroupReceipts.ControlStatus = true;
                            mdlGrouptoDeposit.Show();
                        }
                    }
                    else
                    {
                        uclCommonPopup.Alert("Display Message Box", "Please select same bank account");

                    }
                }
                else
                {
                    uclCommonPopup.Alert("Display Message Box", "Selected items must be receipts");
                }
            }
            else
            {
                uclCommonPopup.Alert("Display Message Box", "At least one receipt must be selected before proceeding");
            }

            //CreateCookie();
         

        }

Saturday, 13 July 2013

SQL server training

create database swapnil
use swapnil

create table emp(empid int,ename varchar(30),eadd varchar(30),city varchar(20),
pin int , join_dt datetime, mobileno int
)

Alter table emp add constraint Pk_empno  primary key (empid)

Alter table emp alter column empid int not null
ALTER TABLE Po_detail  column Po_Pono TO Pd_Pono

Alter table Po_detail Add constraint Pk_Pono_Itemcd primary key(Po_Pono,Pd_itemcd)

Alter table Vendor alter column vn_vendcd int not null
Alter table Vendor Add constraint Pk_vencd primary key(vn_vendcd)

ALTER TABLE Vendor
DROP CONSTRAINT  Pk_vencd
drop table Vendor primary constraint key Pk_vencd

Alter table Item alter column Im_itemcd numeric(18,2) not null
Alter table Item Add constraint Pk_itemcd primary key(Im_itemcd)
Alter table Vendor alter column vn_vendcd numeric(18,2) not null
Alter table PO_Head alter column Ph_vendcd numeric(18,2) not null

Alter table PO_Head add constraint fk_vendc foreign key (Ph_vendcd) references vendor (vn_vendcd)

Alter table emp alter column mobileno int not null

Alter table emp add constraint Uk_mobileno  unique (mobileno)
Alter table emp alter column city varchar(20) not null


ALTER TABLE emp
Add constraint Df_city DEFAULT 'city' for city

Alter table Vendor alter column Im_rate numeric(18,2) not null

insert into Vendor values(1,'Mahalaxmi tradors')
insert into Vendor values(2,'Vikhroli tradors')
insert into Vendor values(3,'bhandup tradors')
insert into Vendor values(4,'Elphiston tradors')
insert into Vendor values(5,'kanjur tradors')

insert into Item values (1,'item1',15)
insert into Item values (2,'item2',20)
insert into Item values (3,'item3',21)
insert into Item values (4,'item4',22)
insert into Item values (5,'item5',23)
insert into Item values (6,'item6',14)
insert into Item values (7,'item7',13)
insert into Item values (8,'item8',12)
insert into Item values (9,'item9',17)
insert into Item values (10,'item10',18)

Alter table Po_detail alter column Pd_value numeric(18,0)  null
insert into Po_detail values(1,1,10,null,null )
insert into Po_detail values(1,2,20 ,null,null)
insert into Po_detail values(1,3,30,null,null )
insert into Po_detail values(2,4,10,null,null )
insert into Po_detail values(2,5,10 ,null,null)
insert into Po_detail values(2,6,10 ,null,null)
insert into Po_detail values(3,7,50,null,null )
insert into Po_detail values(3,8,60,null,null )
insert into Po_detail values(3,9,70,null,null )

insert into Po_detail values(4,10,50,null,null )
insert into Po_detail values(4,11,60,null,null )
insert into Po_detail values(4,12,70,null,null )

insert into Po_detail values(5,13,50 ,null,null)
insert into Po_detail values(5,14,60 ,null,null)
insert into Po_detail values(5,15,70,null,null )


Alter table PO_Head alter column Ph_TaxAmt numeric(18,0)  null
insert into PO_Head values(1,GETDATE(),1,null,null )
insert into PO_Head values(2,GETDATE(),2,null,null )
insert into PO_Head values(3,GETDATE(),3,null,null )
insert into PO_Head values(4,GETDATE(),4,null,null )
insert into PO_Head values(5,GETDATE(),5,null,null )


select * from PO_Head
select * from Vendor
select * from Item
select * from Po_detail

Update Po_detail set Pd_rate =( select im_rate from Item where Im_itemcd = Pd_itemcd)
Update Po_detail set Pd_value = Pd_qty * Pd_rate
Update PO_Head set Ph_Poamnt = (select sum(pd_value)from po_detail  where Ph_Pono = po_pono)

Function in sql

create function third_func
(
@item int)
RETURNs int
as
begin
Declare @rate int
  select @rate =   Im_rate*(Im_rate + 10) from Item where Im_itemcd = @item
   RETURN @rate
End


----------------
select dbo.third_func(1)

sql server login

after create login need to restart sql service