Saturday, 19 November 2011

Quick tip Jquery validation For ASP.net Controls

JQUERY VALIDATION FOR ASP.NET CONTROLS



Jquery Blank Field Validation

if(document.getElementById("<%=CompanyNameTextBox.ClientID %>").value=="")
    {
    alert("Please Enter Company Name");
    document.getElementById("<%=CompanyNameTextBox.ClientID %>").focus();
    return false;
    }




Jquery Contact No Validation



<asp:TextBox ID="ContactNoTextBox" runat="server" onkeypress="return chklen(this);"></asp:TextBox></td>
function chknum3()
{
if((event.keyCode >=48 )&&(event.keyCode<=57))
{
alert("Branch Name Should Be In Character..");
return false;
}
else
{

return true ;
}
}



Jquery Number Length Validation



function chklen(id)
{
if  (id.value.length <11)
{
return chknum();
}
else
{
alert("Mobile Number Length should not be greater than 11 Digits::::");
return false;
}
}





Jquery Email Validation
 if(document.getElementById("<%=EmailTextBox.ClientID%>").value=="")
     {
      alert("Please Enter EMail Id....")
      return false
     }
     else
      {
      var at="@"
      var dot="."
      var str=document.getElementById("<%=EmailTextBox.ClientID%>").value;
      var lstr=str.length;
      var lat=str.indexOf(at);
      var ldot=str.indexOf(dot);
      var pat=/^.+@.+\..{2,3}$/;
 
      if(str.indexOf(at)==-1 ||str.indexOf(at)==0 ||str.indexOf(at)==lstr)
      {
      alert("Invalid Email Id.. Please Try Again..")
      return false;
      }
      if(str.indexOf(dot)==-1||str.indexOf(dot)==0||str.indexOf(dot)==lstr )
      {
      alert("Invalid Email Id.. Please Try Again..")
      return false;
      }
     }






Jquery Delete/Confirmation:
  function del()
    {
    if(confirm("Are You Sure?")==true)
    {return true;
   
        }
        else
        {
        return false;
        }
    }


onclientclick="return del()";






Jquery ToolTip:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.qtip-1.0.0-rc3.min.js"></script> 
   
   
   
    <script type="text/javascript">
// Create the tooltips only on document load
$(document).ready(function()
{
   // Notice the use of the each() method to acquire access to each elements attributes
   $('.show-tooltip').each(function()
   {
      $(this).qtip({
         content: 'be a good one', // Use the tooltip attribute of the element for the content
         style: 'dark' // Give it a crea mstyle to make it stand out
      });
   });
});
</script>


<a href="http://google.com/" class="show-tooltip" ><asp:Button ID="Button1" runat="server" Text="Love" /></a>
    



Jquery Hide and Show via flipping:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".flip").click(function(){
    $(".panel").slideToggle("slow");
  });
});
</script>

<style type="text/css">
p.flip
{
margin:0px;
padding:5px;
text-align:center;

border:solid 1px #c3c3c3;
}
div.panel
{
            height:163px;
        width: 1268px;
       display:none;
 <%--optional to fill color--%>background-color:Lime;
       
}
</style>



<input id="Button1" type="button" value="button" class="flip" />
<div class="panel">Anything</div>





Jquery Hide and Show via flipping:

SHORT WINDOW OPEN CLOSE
 <script type="text/javascript">  
   function closepopup()
   {
     
        window.close();
    
   }</script> 
on cs.file................................................
 string scrname;
         scrname = @"<SCRIPT language='javascript'> closepopup();" + "</SCRIPT>";
            this.RegisterStartupScript("MyAlert", scrname);










Jquery open window pop up
<script type="text/javascript">
<!--
function popup(url)
{
 var width  = 500;
 var height = 270;
 var left   = (screen.width  - width)/2;
 var top    = (screen.height - height)/2;
 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=no';
 params += ', status=no';
 params += ', toolbar=no';
 newwin=window.open(url,'windowname5', params);
 if (window.focus) {newwin.focus()}
 return false;
}
// -->
</script>
<a href="javascript: void(0)"
   onclick="popup('addexam1.aspx')">click here to view</a>




Increment looping starts from '00' Like 001 to 096...

increment looing
 
SqlCommand cmd1 = new SqlCommand("select * from tbMemberRegistration where MemberShipNo like (@check)", cstring);
string dd = (LastNameTextBox.Text.Substring(0, 1) + "%").ToString();
cmd1.Parameters.Add("@check",SqlDbType.VarChar).Value = (LastNameTextBox.Text.Substring(0, 1) + "%").ToString();
                              SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
int count = Convert.ToInt32(ds1.Tables[0].Rows.Count.ToString());
if (ds1.Tables[0].Rows.Count == 0)
{
//Labelexd.Text = LastNameTextBox.Text.Substring(0, 1);
string st = LastNameTextBox.Text.ToUpper().Substring(0, 1);
code = st + "00" + (count + 1);
}
if (count > 0 && count < 9)
{
string st = LastNameTextBox.Text.ToUpper().Substring(0, 1);
code = st + "00" + (count + 1);
}
if (count >= 9 && count < 99)
{
string st = LastNameTextBox.Text.ToUpper().Substring(0, 1);
code = st + "0" + (count + 1);
}
if (count >= 99 && count < 999)
{
string st = LastNameTextBox.Text.ToUpper().Substring(0, 1);
code = st + (count + 1);
}

Friday, 11 November 2011

Crystal Report Basic Sample

 
7 Easy Steps to get start with Crystal Report.


To Start With You Shold Have A Table In your Database.





Before I start I would like to recommend new kind of reporting which is which is currently a hot topic in IT industry, that is Power bi,and you can head start with it by viewing this popular video on power bi which can make you power bi professional in very simple stepsas below.




1)Open visual studio...then create website

2)Now open  toolbox,go on Reporting TAB,Add Crystal Report Viewer To Any Of Your Blank ASPX page,
(if only Pointer And MicrosoftViewer Is Present or If Crystal Report Is Not Existed In the Reporting TAB.Go through the VISUAL STUDIO SET UP AGAIN AND CHOOSE  ADD NEW ITEM instead of UPDATE OPTION THIS TIME and you'll see in the installation list crystal report is in the last!)



2)Now After You Drag The Crystal Report Viewer Control you'll get a control in your page with name 'CrystalReportViewer1')

Now right click to your solution add new item and select CrystalReport.this will add crystal report to  your solution (as you add webform or any file) wth name 'CrystalReport.rpt'

Now You Have
a Crystal Report (CrystalReport.rpt)
And
a Crystal Report Control (CrystalReportViewer1)In a Form Who Can Handle It.




3)Now When You Open Crystal Report  The Screen Will Look Some Thing Like This



 
4)Now You’ll Find Field Explorer side bar in right with solution Explorer As Shown open it and right click Database Field




5) After That A New Window Will open ‘DATABASE EXPERT’

Now Here  Is The Thing You Have To Go Smoothly.
Click ‘create new connection’ + sign
then + sign of OL EDB ADO



then a window will appear which wil ask you to set your database path...

make proper connection…
After that your database will get generate on right hand side pane.





Click > and transfer your database to 'selected table' box(on right hand side)
Click table name press ok

and you have done 90% of work!






6)
Now just Explore database field of field explorer(Field Explorer  Only Appears in CrytalReport) and drag coloumn name to the Crystal report .
wherever you want
(Coloum automaticly behave as they are bind in gridview or datalist)




Check the toolbox you have four tools to design.










7)
Write this code in form .cs file where the control exist

i)add these namespaces must


using System.IO;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.Enterprise;
using CrystalDecisions.ReportSource;



ii)and continue to this as you understand

Now the basic thing you have to do is Binding Your Database Value to Crystal Report!
if You Understand the basic binding you can easily notice that i 've just binded values to crytal report!


public void NormalBinding()
{

SqlCommand sqlcmd = new SqlCommand("
select * from sample", con);SqlDataAdapter  da = new SqlDataAdapter(sqlcmd); 
DataTable dt = new DataTable();
dt.Clear();
da.Fill(dt);


if (dt.Rows.Count > 0)
{
ReportDocument RptDoc = new ReportDocument();

RptDoc.Load(Server.MapPath("CrystalReport.rpt"));
RptDoc.SetDataSource(dt);

CrystalReportViewer1.ReportSource = RptDoc;
CrystalReportViewer1.DataBind();

}

                            



Above one is all about a function  NormalBinding() who's used to bind data in crystal report!      
you can take a look to basic binding on my basic asp.net post.



Now Your Whole Project Will Look Some thing Like This.

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

<%@ Register Assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
    Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />
    </div>
    </form>
   
</body>
</html>

.CS FILE
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.Enterprise;
using CrystalDecisions.ReportSource;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection sconn = new SqlConnection(ConfigurationManager.AppSettings["regattacon"]);
    string sid;
    SqlDataAdapter da;
    string query;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
         
            bindproformainvoicepi_no();

        }
    }

    public void bindproformainvoicepi_no()
    {

        query = "select * from sample";
        SqlCommand sqlcmd = new SqlCommand(query, sconn);

        da = new SqlDataAdapter(sqlcmd); DataTable dt = new DataTable();
        dt.Clear();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            ReportDocument RptDoc = new ReportDocument();

            RptDoc.Load(Server.MapPath("CrystalReport.rpt"));
            RptDoc.SetDataSource(dt);

            CrystalReportViewer1.ReportSource = RptDoc;
            CrystalReportViewer1.DataBind();
          


        }
    }
}






RUN it and have fun with CRYSTAL REPORT,with its nice printing,exporting to excel,pdl,doc ,style












Sunday, 6 November 2011

Common Javascript Solutions



only number validation
    <script>
function checkForInt(evt)
{
var charCode = ( evt.which ) ? evt.which : event.keyCode;
return ( charCode >= 48 && charCode <= 57 );
}
</script>


 onkeypress="return checkForInt(event)"

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


function checknum()
{
if((event.keyCode >=48 )&&(event.keyCode<=57))
{
return true;
}
else
{
alert("Please Enter Only Numeric Values..");
return false ;
}
}


onkeypress="return checknum();"


-------------------------------------------
function checklength(id)
{
if  (id.value.length <11)
{
return chknum();
}
else
{
alert("Mobile Number cant not be greater than 11 Digits:::");
return false;
}
}


-------------------------------------------------
function blank()
{
if(document.getElementById("<%=TextBox1.ClientID %>").value=="")
{
alert("Cant be Blank not be blank!");
document.getElementById("<%=TextBox1.ClientID %>").focus();
return false ;
}
return true;
}







-----------------------------------------------------------------
               Email Validations 
function email()
{


  var at="@"
  var dot="."
  
  var str=document.getElementById("<%=EmailIDTextBox.ClientID%>").value;
  var lstr=str.length;
  var lat=str.indexOf(at);
  var ldot=str.indexOf(dot);
  var pat=/^.+@.+\..{2,3}$/;
  
  if(str.indexOf(at)==-1 ||str.indexOf(at)==0 ||str.indexOf(at)==lstr)
  {
  alert("Invalid EmailId..")
  document.getElementById("<%=EmailIDTextBox.ClientID %>").focus();
  return false;
  }
  if(str.indexOf(dot)==-1||str.indexOf(dot)==0||str.indexOf(dot)==lstr )
  {
  alert("Invalid EmailId..")
  document.getElementById("<%=EmailIDTextBox.ClientID %>").focus();
  return false;
  }
  


return true ;
}


                                   or  






Email Validation
 if(document.getElementById("<%=EmailTextBox.ClientID%>").value=="")
     {
      alert("Please Enter EMail Id....")
      return false
     }
     else
      {
      var at="@"
      var dot="."
      var str=document.getElementById("<%=EmailTextBox.ClientID%>").value;
      var lstr=str.length;
      var lat=str.indexOf(at);
      var ldot=str.indexOf(dot);
      var pat=/^.+@.+\..{2,3}$/;

      if(str.indexOf(at)==-1 ||str.indexOf(at)==0 ||str.indexOf(at)==lstr)
      {
      alert("Invalid Email Id.. Please Try Again..")
      return false;
      }
      if(str.indexOf(dot)==-1||str.indexOf(dot)==0||str.indexOf(dot)==lstr )
      {
      alert("Invalid Email Id.. Please Try Again..")
      return false;
      }
     }



                         (both are same)


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


function date()
{
if(document.getElementById("<%=.ClientID %>").value=="")
{
alert("Please Select The Date From Calendar");


return false ;
}
return true;
}

Common SQL Solutions



1)insert one table into other directly in sql

insert into tbl_Processing (Process_ID,ArrivalId,Adate,BoxDesignId,Qty,Rate,Total) SELECT   Process_ID,ArrivalId,Adate,BoxDesign,Qty,Rate,TotalBoxAmount FROM  temp_BoxProcessing


2)UNION two table
select * from(select * from TrainingSessionSummerTrainView  union select * from TrainingSessionIndusView )a where orgfu_org_name=1

3) Versions error
Unfortunatly it is due to old version of sql eg.2000

 and you are trying to implement something which was not available on that time...
leave it whatever it was the solution is
just replace [dbo] from your table even [ ] these brackets from your table name
(its a solution for one of its kind,you may have other prob.,let me know if any)


ask me if any further question you have...

4)Date differences in SQL


SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(getDate())-1),getDate()),101)



5)Create New Table (A CLONE COPY OF EXISTING TABLE)

SELECT   * 
INTO           New_Table
FROM         Exisiting_Table

6)What to Show When There Is NO Value returning in row?

suppose the query is ...

select price from tableproduct where id='123'


and there is no id with 123
then you will get a single row in result with NULL

but you further need some calculation with this output so just make NULL to 0 by this query...

select MAX(isnull(pattern,0)) from tbl_rueno where pi_no='1111'

 but be careful if the data type of the selected field is non int,
you should make column data type any datatype to int,so we did bit modification below to do so...


MAX(isnull(convert(int,crate_to),0))+1 from tbl_rueno where pi_no='1111'






Common Small Solutions C#.Net


find control on footrow of gridview

Label7.Text =((Label)GridViewBoxTemp.FooterRow.Cells[2].FindControl("FootLabelRate")).Text;


In Row Bound

 Label lblTotalPrice = (Label)e.Row.FindControl("LabelTQ");

In normal

((Label)GridView1.Rows[e.RowIndex].FindControl("Labelid")).Text);


Return 0 if field value is null
select Max(isnull(Process_ID,0)) as process from tbl_Processing




Date time Exceed by months

using System.Globalization;

  protected void DropEMISchedule_SelectedIndexChanged(object sender, EventArgs e)
    {
        DateTime dt;
       
        int calcy = Convert.ToInt32(DropEMISchedule.SelectedValue) * Convert.ToInt32(txttenure.Text);
        if (DateTime.TryParseExact(txtEMIStartDate.Text, "dd/MM/yyyy",new CultureInfo("en-US"), System.Globalization.DateTimeStyles.None, out dt))
        {
            TextBoxend.Text = "";
            DateTime dtshow = dt.Date.AddMonths(calcy);
            TextBoxend.Text = (dtshow).ToString("dd/MM/yyyy");
        
        }

      
      
    }




Pass Dataset in Session From One Page To Another




just add this
dataset st;
st=(DataSet)Session["SelectionD"];


to make dataset know what kind of value its in session





 No Datasource type display in data source configruation wizard

Its Due to the Becoz you have added chart controls(or any thing)
and you forget to see that there is some thing wrong in toolbox on left side pane!
so just open it!
got it?
Actually you have two tabs with same name 'Data' just right click on the new tab(like tab which contain chart control) and rename it to any thing else like i have changed it to 'Chart Data'!
It will work fine!
ask me if you have any question!


Execute Scaler Use To Count Rows

SqlCommand cmd = new SqlCommand("select count(EnrollmentNo) From Admission where EnrollmentNo='" + txt_enrollmentno.Text + "'", con);
      
int count = Convert.ToInt32(cmd.ExecuteScalar());

        if (count != 0)
        {

            //You Have Entered Enrollment No Which Is Already Exist Please Enter Diffrent Enrollment No!'

        }
        else
        {
           //'Valid Enrollment ....You Can Proceed
        }


Add value to SqlCommand :
cmd.Parameters.AddWithValue("@userName", userName);



Substring Value

int ind = 0;

 int len =4;
Label1.Text = TextBox1.Text.Substring(ind, len);

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...