Saturday, June 21, 2014

JQuery/JavaScript Tips n Tricks

1. Check Radio button list value using JQuery and display message.

function rblStatus()
{
     var rss = $('#<%=RadioButtonList.ClientID %> input[type=radio]:checked').val();
     if (rss != 'Pending' && rss != 'Updated' && rss != 'Disapproved')
     {
          msg = "Please Select Status";
          alert(msg);
          return false;
      }
      else
     {
          return true;
     }
 }

2. Jquery Code to check all checkboxes in a gridview

function SelectAllCheckboxes(chk)
{
    $('#<%=gridview.ClientID%>').find("input:checkbox").each(function ()
    {
      if (this != chk) { this.checked = chk.checked; }
    });
}

3. Show / Hide Any server control using Jquery

$("#<%=ASPControlName.ClientID%>").css("display", "none");  //Hide
$("#<%=ASPControlName.ClientID %>").css("display", "block"); //Show

4. Uncheck ASP RadioButtonList

$("table[id$=ASPControlName] input:radio:checked").removeAttr("checked")

5. Assign Value to an ASPControl

$("#<%=ddlStatus.ClientID %>").val('USERVALUE');  //USERVALUE can be any varchar value.


6. Find Gridview row count

 var gvCount = $("#<%=Gridview.ClientID %> tr").length;
  if (gvCount > 0)
 {
     alert("Count is:"+gvCount );
  }
  else
 {
     alert("No rows available");
 }

7. Print data in using client side Code using JavaScript

Step 1: Create table to be displayed under div.

     <div id="div1" runat="server" visible="false">
      <table border="1" cellpadding="1" cellspacing="1" id="PrintSlot" align="center">
        <tr>
           <td align="center" >
             <asp:Label ID="Label6" runat="server" Text="Print Me"></asp:Label>
           </td>
        </tr>
     </table>
   </div>

Step 2: JavaScript Function to print the content.

    function printData()
    {
            var divToPrint = document.getElementById("PrintSlot");  // Pass ID of table
            newWin = window.open("");
            newWin.document.write(divToPrint.outerHTML);
            newWin.print();
    }

Display Checkbox in Telerik RadCombobox and select any specific value using JQuery

Step 1: Display checkbox in Telerik Combobox 

<telerik:RadComboBox ID="ddlStream" runat="server" EmptyMessage="Type Program Name" DataTextField='Program' DataValueField='Code' Style="display: none; width: 300px;" ZIndex="999999" Filter="Contains">
 <ItemTemplate>
   <asp:CheckBox runat="server" ID="chk1" Width="300" Text='<%#Eval("Program") %>' onclick="onCheckBoxClick(this)" />
 </ItemTemplate>
</telerik:RadComboBox>

Step 2: Function to select any checkbox in the RadCombobox

function onCheckBoxClick(element) {
            var text = "";
            var values = "";

            var combo = $find("<%= ddlStream.ClientID %>");
            var items = combo.get_items();

            for (var i = 0; i < items.get_count() ; i++) {
                var item = items.getItem(i);


                var chk1 = $get(combo.get_id() + "_i" + i + "_chk1");
                if (chk1.checked) {
                    text += item.get_text() + ",";    
                         //Text of selected checkbox of ComboBox
                    values += item.get_value() + ", ";   
                         // Values of selected checkbox of ComboBox
                }
            }

            text = removeLastComma(text);
            $("#<%=txtBox.ClientID %>").val(text);  // Text generated above displayed in textbox.
            prg = text;
        }

        //This method removes the ending comma from a string.
        function removeLastComma(str) {
            return str.replace(/,$/, "");
        }

Step 3. (OPTIONAL) CSS changes that may be required to display the combobox if displayed in popup (Values added need to be updated as per requirement.)

<style type="text/css">
        .RadComboBoxDropDown
        {
            z-index: 999999999999 !important;
        }

        #ctl00_ContentPlaceHolder1_ddlStream_DropDown
        {
            width: 320px !important;
        }

        .rcbFocused
        {
            width: 320px !important;
        }

        #ctl00_ContentPlaceHolder1_ddlStream table
        {
            width: 320px !important;
        }
</style>

Tuesday, June 17, 2014

Fetch value from SQL DataSource and use select command to fetch individual row details.

DataView dv = (DataView)SqlDataSource.Select(DataSourceSelectArguments.Empty);
int reorderedProducts = (int)dv.Table.Rows[0][2];

DataRow[] dr = dv.Table.Select("Code='" + val + "'");
string id = dr[0]["Id"].ToString();


Code to fetch Data from database using SQL DataAdaptor and fill DataSet

if (con.State == ConnectionState.Closed)
        {
            con.Open();   // check connection and if closed then open it.
        }
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //Connection object
cmd.CommandText = "Stored Procedure Name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Id", SqlDbType.NVarChar).Value = Convert.ToInt32(id); //Parameter
SqlDataAdapter adt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adt.Fill(ds);


Code to save data into database

if (con.State == ConnectionState.Closed)
        {
            con.Open();   // check connection and if closed then open it.
        }
SqlCommand cmd = new SqlCommand(); // Declare Sqlcommand Function
cmd.Connection = con;
cmd.CommandText = "Stored Procedure Name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.NVarChar).Value = txtbox.Text;
cmd.Parameters.Add("@ErrorStatus", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
if (Convert.ToInt32(cmd.Parameters["@ErrorStatus"].Value) == 1)
   {
      reset();
      DisplayAJAXMessage(this, "Inserted Successfully");
   }

To display message in popup

static public void DisplayAJAXMessage(Control page, string msg)
    {
        string myScript = String.Format("alert('{0}');", msg);
        ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);
    }

Telerik Radgridview methods and functions summary:

Telerik Radgridview Operations: (Here grid name is radgrid)

1. Fetch Specific row details by clicking on link button in the row:

((sender as LinkButton).Parent.Parent as GridItem).Selected = true;
String ID = ((radgrid.SelectedItems[0].FindControl("lblID") as Label).Text).ToString();
 OR
HiddenField hdnId = radgrid.SelectedRow.FindControl("hdnId") as HiddenField;

2. Code to change pages in radgrid using page index changed event:

 protected void radgrid_PageIndexChanged(object sender, Telerik.Web.UI.GridPageChangedEventArgs e)
    {
        radgrid.DataSource = (DataSet)Session["data"];
        radgrid.DataBind();
    }

3. Code to change the grid page size to be displayed using page size changed event:

protected void radgrid_PageSizeChanged(object sender, Telerik.Web.UI.GridPageSizeChangedEventArgs e)
    {
        radgrid.DataSource = (DataSet)Session["data"];
        radgrid.DataBind();
    }

4. Code to enable filter option with the help of item command event:

protected void radgrid_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "Filter")
        {
            radgrid.DataSource = (DataSet)Session["data"];
            radgrid.DataBind();
        }
    }

5. Code to export radgridview data to excel file:

 protected void btnExcel_Click(object sender, EventArgs e)
    {
        radgrid.ExportSettings.ExportOnlyData = true;
        radgrid.ExportSettings.IgnorePaging = true;
        radgrid.DataSource = (DataSet)Session["data"];
        radgrid.DataBind();
        radgrid.ExportSettings.OpenInNewWindow = true;
        radgrid.ExportSettings.FileName = "FileName";
        if (radgrid.Items.Count > 0)
        {
            radgrid.MasterTableView.ExportToExcel();
        }
    }

6. Design code to add column in the radgridview:



 <%# Container.DataItemIndex +1 %>
 




7. Design code to Make a GridView Column Visible using fetched value:


 
        LinkButton_Click" Text="Print" Visible='<%# (bool.Parse(Eval("IsVisible").ToString())) %>' ToolTip='<%# Eval("Id") %>'>




Saturday, June 21, 2014

JQuery/JavaScript Tips n Tricks

1. Check Radio button list value using JQuery and display message.

function rblStatus()
{
     var rss = $('#<%=RadioButtonList.ClientID %> input[type=radio]:checked').val();
     if (rss != 'Pending' && rss != 'Updated' && rss != 'Disapproved')
     {
          msg = "Please Select Status";
          alert(msg);
          return false;
      }
      else
     {
          return true;
     }
 }

2. Jquery Code to check all checkboxes in a gridview

function SelectAllCheckboxes(chk)
{
    $('#<%=gridview.ClientID%>').find("input:checkbox").each(function ()
    {
      if (this != chk) { this.checked = chk.checked; }
    });
}

3. Show / Hide Any server control using Jquery

$("#<%=ASPControlName.ClientID%>").css("display", "none");  //Hide
$("#<%=ASPControlName.ClientID %>").css("display", "block"); //Show

4. Uncheck ASP RadioButtonList

$("table[id$=ASPControlName] input:radio:checked").removeAttr("checked")

5. Assign Value to an ASPControl

$("#<%=ddlStatus.ClientID %>").val('USERVALUE');  //USERVALUE can be any varchar value.


6. Find Gridview row count

 var gvCount = $("#<%=Gridview.ClientID %> tr").length;
  if (gvCount > 0)
 {
     alert("Count is:"+gvCount );
  }
  else
 {
     alert("No rows available");
 }

7. Print data in using client side Code using JavaScript

Step 1: Create table to be displayed under div.

     <div id="div1" runat="server" visible="false">
      <table border="1" cellpadding="1" cellspacing="1" id="PrintSlot" align="center">
        <tr>
           <td align="center" >
             <asp:Label ID="Label6" runat="server" Text="Print Me"></asp:Label>
           </td>
        </tr>
     </table>
   </div>

Step 2: JavaScript Function to print the content.

    function printData()
    {
            var divToPrint = document.getElementById("PrintSlot");  // Pass ID of table
            newWin = window.open("");
            newWin.document.write(divToPrint.outerHTML);
            newWin.print();
    }

Display Checkbox in Telerik RadCombobox and select any specific value using JQuery

Step 1: Display checkbox in Telerik Combobox 

<telerik:RadComboBox ID="ddlStream" runat="server" EmptyMessage="Type Program Name" DataTextField='Program' DataValueField='Code' Style="display: none; width: 300px;" ZIndex="999999" Filter="Contains">
 <ItemTemplate>
   <asp:CheckBox runat="server" ID="chk1" Width="300" Text='<%#Eval("Program") %>' onclick="onCheckBoxClick(this)" />
 </ItemTemplate>
</telerik:RadComboBox>

Step 2: Function to select any checkbox in the RadCombobox

function onCheckBoxClick(element) {
            var text = "";
            var values = "";

            var combo = $find("<%= ddlStream.ClientID %>");
            var items = combo.get_items();

            for (var i = 0; i < items.get_count() ; i++) {
                var item = items.getItem(i);


                var chk1 = $get(combo.get_id() + "_i" + i + "_chk1");
                if (chk1.checked) {
                    text += item.get_text() + ",";    
                         //Text of selected checkbox of ComboBox
                    values += item.get_value() + ", ";   
                         // Values of selected checkbox of ComboBox
                }
            }

            text = removeLastComma(text);
            $("#<%=txtBox.ClientID %>").val(text);  // Text generated above displayed in textbox.
            prg = text;
        }

        //This method removes the ending comma from a string.
        function removeLastComma(str) {
            return str.replace(/,$/, "");
        }

Step 3. (OPTIONAL) CSS changes that may be required to display the combobox if displayed in popup (Values added need to be updated as per requirement.)

<style type="text/css">
        .RadComboBoxDropDown
        {
            z-index: 999999999999 !important;
        }

        #ctl00_ContentPlaceHolder1_ddlStream_DropDown
        {
            width: 320px !important;
        }

        .rcbFocused
        {
            width: 320px !important;
        }

        #ctl00_ContentPlaceHolder1_ddlStream table
        {
            width: 320px !important;
        }
</style>

Tuesday, June 17, 2014

Fetch value from SQL DataSource and use select command to fetch individual row details.

DataView dv = (DataView)SqlDataSource.Select(DataSourceSelectArguments.Empty);
int reorderedProducts = (int)dv.Table.Rows[0][2];

DataRow[] dr = dv.Table.Select("Code='" + val + "'");
string id = dr[0]["Id"].ToString();


Code to fetch Data from database using SQL DataAdaptor and fill DataSet

if (con.State == ConnectionState.Closed)
        {
            con.Open();   // check connection and if closed then open it.
        }
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //Connection object
cmd.CommandText = "Stored Procedure Name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Id", SqlDbType.NVarChar).Value = Convert.ToInt32(id); //Parameter
SqlDataAdapter adt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adt.Fill(ds);


Code to save data into database

if (con.State == ConnectionState.Closed)
        {
            con.Open();   // check connection and if closed then open it.
        }
SqlCommand cmd = new SqlCommand(); // Declare Sqlcommand Function
cmd.Connection = con;
cmd.CommandText = "Stored Procedure Name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.NVarChar).Value = txtbox.Text;
cmd.Parameters.Add("@ErrorStatus", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
if (Convert.ToInt32(cmd.Parameters["@ErrorStatus"].Value) == 1)
   {
      reset();
      DisplayAJAXMessage(this, "Inserted Successfully");
   }

To display message in popup

static public void DisplayAJAXMessage(Control page, string msg)
    {
        string myScript = String.Format("alert('{0}');", msg);
        ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);
    }

Telerik Radgridview methods and functions summary:

Telerik Radgridview Operations: (Here grid name is radgrid)

1. Fetch Specific row details by clicking on link button in the row:

((sender as LinkButton).Parent.Parent as GridItem).Selected = true;
String ID = ((radgrid.SelectedItems[0].FindControl("lblID") as Label).Text).ToString();
 OR
HiddenField hdnId = radgrid.SelectedRow.FindControl("hdnId") as HiddenField;

2. Code to change pages in radgrid using page index changed event:

 protected void radgrid_PageIndexChanged(object sender, Telerik.Web.UI.GridPageChangedEventArgs e)
    {
        radgrid.DataSource = (DataSet)Session["data"];
        radgrid.DataBind();
    }

3. Code to change the grid page size to be displayed using page size changed event:

protected void radgrid_PageSizeChanged(object sender, Telerik.Web.UI.GridPageSizeChangedEventArgs e)
    {
        radgrid.DataSource = (DataSet)Session["data"];
        radgrid.DataBind();
    }

4. Code to enable filter option with the help of item command event:

protected void radgrid_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "Filter")
        {
            radgrid.DataSource = (DataSet)Session["data"];
            radgrid.DataBind();
        }
    }

5. Code to export radgridview data to excel file:

 protected void btnExcel_Click(object sender, EventArgs e)
    {
        radgrid.ExportSettings.ExportOnlyData = true;
        radgrid.ExportSettings.IgnorePaging = true;
        radgrid.DataSource = (DataSet)Session["data"];
        radgrid.DataBind();
        radgrid.ExportSettings.OpenInNewWindow = true;
        radgrid.ExportSettings.FileName = "FileName";
        if (radgrid.Items.Count > 0)
        {
            radgrid.MasterTableView.ExportToExcel();
        }
    }

6. Design code to add column in the radgridview:



 <%# Container.DataItemIndex +1 %>
 




7. Design code to Make a GridView Column Visible using fetched value:


 
        LinkButton_Click" Text="Print" Visible='<%# (bool.Parse(Eval("IsVisible").ToString())) %>' ToolTip='<%# Eval("Id") %>'>