Tuesday 20 December 2011

How to create a Trigger in MS SQLSERVER 2005

--create table employee_personal_Details
--(EmpID int Not Null,
--FirstName varchar (30) Not Null,
--LastName Varchar (30) Not Null,
--Age int Not Null
--)

--create table employee_Salary_Details
--(EmpID int Not Null,
--Job varchar (30) Not Null,
--Hiredate datetime Not Null,
--salary int Not Null
--)
Create trigger employee_deletion
on 
employee_personal_Details
after delete
as
begin
print ' deletion will affect employee_Salary_Details table'
Delete from employee_Salary_Details where EmpID in
(Select EmpID from deleted)
End

Saturday 17 December 2011

The relationshipe between Connection,Command,DataAdapter,DataSet Objects

 
SqlConnection scon = new SqlConnection("database=StudentDB;trusted_connection=yes");
SqlCommand scmd = new SqlCommand("select* from StudentInfoTable", scon);
SqlDataAdapter sda = new SqlDataAdapter(scmd);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();

// And finally  giving the object of DataSet to the Gridview having ID="Gridview1"  last two line to bind the Dataset to the Gridview.

Friday 16 December 2011

Data Source Controls in ASP.net


Data source controls:-
 SSql Data Source
    Access Data Source
   Object Data Source
 XML Data Source
        SSite Map Data Source
Data Web Controls/Data Bound Controls:-
 Grid View  Control
   Details View Control
Form View control
         Radio Button List Control
        Drop Down List  Control


Graphical Communication
Between
 Data Source Controls and Data Bound Control

  Data Bound control           DataSource Controls                         Data Source
 Grid View    message to     Data Source Controls   message to   Business Object or DB
                                                           
The communication between the Web controls/Data Bound controls  and Data Source Control  is two way.

Thursday 15 December 2011

Best Example found on MSDN help Using GridView in ASP.net and its properties

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Button ID="CheckAll" runat="server" Text="Check All" OnClick="CheckAll_Click" />
<asp:Button ID="UncheckAll" runat="server" Text="Uncheck All" OnClick="UncheckAll_Click" />
<asp:GridView ID="Products" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"DataSourceID="ProductsDataSource" AllowPaging="True" EnableViewState="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ProductSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="Price"HtmlEncode="False" SortExpression="UnitPrice" /></Columns></asp:GridView>
<asp:ObjectDataSource ID="ProductsDataSource" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetProducts" TypeName="ProductsBLL"> </asp:ObjectDataSource>
<asp:Button ID="DeleteSelectedProducts" runat="server" Text="Delete Selected Products" OnClick="DeleteSelectedProducts_Click" />
<asp:Label ID="DeleteResults" runat="server" EnableViewState="False" Visible="False"></asp:Label></asp:Content>

protected void DeleteSelectedProducts_Click(object sender, EventArgs e)
{
bool atLeastOneRowDeleted = false;

// Iterate through the Products.Rows property
foreach (GridViewRow row in Products.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
if (cb != null && cb.Checked)
{
// Delete row! (Well, not really...)
atLeastOneRowDeleted = true;

// First, get the ProductID for the selected row
int productID = Convert.ToInt32(Products.DataKeys[row.RowIndex].Value);

// "Delete" the row
DeleteResults.Text += string.Format("This would have deleted ProductID {0}<br />", productID);

//... To actually delete the product, use ...
//ProductsBLL productAPI = new ProductsBLL();
//productAPI.DeleteProduct(productID);
//............................................
}//end if
}//end for

// Show the Label if at least one row was deleted...
DeleteResults.Visible = atLeastOneRowDeleted;
}//end function

Wednesday 14 December 2011

Deletion with Php using checkbox with rows named as delete.php

<?php

$username = "328_tahir";
$password = "tahir";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
  or die("Unable to connect to MySQL");
echo "Connected to MySQL now you can create Table new one  <br>";
//select database
mysql_select_db("328_tahir",$dbhandle);
echo "data Base Selected";


 if($_POST['delete']) // from button name="delete"
 {
  $checkbox = $_POST['checkbox']; //from name="checkbox[]"
  $countCheck = count($_POST['checkbox']);
 
  for($i=0;$i<$countCheck;$i++)
  {
   $del_id  = $checkbox[$i];
  
   $sql = "DELETE from products where id = $del_id";
   $result =mysql_query($sql,$dbhandle) or die("cannot delete");
  
  }
 
                 if($result){
    header('Location: index3.php');
   }
   else
   {
    echo "Error: ".mysql_error();
   }
 }
?>

Database connection and displayRecords with checkboxes for deletion per row Using PHP

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Multiple Rows using PHP and MySQL</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />

</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js%22%3E%3C/script>
<script>
$(document).ready(function() {
$("tr:nth-child(even)").addClass("even");
 });

</script>
<div id="container">
 <div id="listing">
    <h1>Delete Multiple Rows Example</h1>
    <!-- now we need to loop throguh and display our fields -->
 <?php
$username = "328_tahir";
$password = "tahir";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
  or die("Unable to connect to MySQL");
echo "Connected to MySQL now you can create Table new one  <br>";
//select database
mysql_select_db("328_tahir",$dbhandle);
echo "data Base Selected";
$query = "SELECT * FROM products";

// run the query and store the results in the $result variable.
$result =mysql_query($query,$dbhandle) or die("cannot do the query");

if ($result) {
  // create a new form and then put the results
  // indto a table.
  echo "<form method='post' action='delete.php'>";
  echo "<table cellspacing='0' cellpadding='15'>
   
    <th width='15%'>Image</th>
    <th width='55%'>Title</th>
  <th width='15%'>Price</th>
  <th width='15%'>Delete</th>
  ";


  while ($row = mysql_fetch_array($result)) {

  $title = $row['product_title'];
  $price = $row['product_price'];
  $image = $row['product_img'];
  $id = $row['id'];
  //put each record into a new table row with a checkbox
 echo "<tr>
   <td><img src='$image' /></td>
   <td>$title</td><td>$price</td>
   <td><input type='checkbox' name='checkbox[]' id='checkbox[]'  value=$id />
   </tr>";

    }

 // when the loop is complete, close off the list.
 echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items'/></p></form>";
}

?>
 </div>
</div><!-- end container -->
</body>
</html>

Monday 12 December 2011

About Data Source Controls

Data Source Controls provides a way of  populating controls with data declaratively,
Controls that support data Binding  have a property and  a method
1) Data Source Property (May be populated by array,DataReader, DataSet (Collections of data such as  an array or DataSet))
2) DataBind() method.

Server Controls support data binding , including simple controls, such as

1)   ListBox
2)  GridView
3 ) DetailsView and ect.


Declarative data binding with sqlDataSource example
<asp:GridView ID="123Gridview" runat="server" DataSourceID="123DataSource"/>
<asp:SqlDataSource ID="123DataSource" runat ="server"
   DataSourcePublish PostMode="DataReader"
 ConnectionString="DataBase="pubs;trusted_connection=yes"
 SelectCommand="Select *from Authors"/>


Imperative Data Binding

<%@page Language="C#" %>
<% import Namespace="System.Data.SqlClient" %>

<script  runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
        {
       using (SqlConnection con= new SqlConnection("database=pubs;trusted_connection=yes"))
       using (SqlCommand cmd= new SqlCommand("select * from authors",con))

          {
   con.Open();
   SqlDataReader reader=cmd.ExecuteReader();
  123GridView.DataSource=reader;
 123GridView.DataBind();
        }
}
</script>
<html>
<head runat="server">
<title>ImperativeDataBinding</title>
</head>
<body>
<form id="f1" runat="server">
<div> <asp:Gridview runat="server  id="123GridView"  /> </div>
</form>
</body>


The above code show  Gridview bound to  atuthors table in pubs databse in swql uses a Data Reader to retrieve the data .



Saturday 10 December 2011

Simple Page of aspx using server controls of List


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SimpleWebSite._Default" %>

<script runat="server">
const int ItemCount=10;

    String GetDisplayItem(int n){
    return "TahirListItem#"+n.ToString();
     }

    protected override void OnLoad(EventArgs e)
    {
        //Clear out Items populated by static declaration

        DisplayList.Items.Clear();

        for (int i = 0; i < ItemCount; i++)
            DisplayList.Items.Add(new ListItem(GetDisplayItem(i)));

        tahirHeading.InnerHtml = "Total number of Item=" + ItemCount.ToString();
           
        base.OnLoad(e);
    }
   
   
   
   
       
</script>

<!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>Tahir Khalid Simple Asp.net in C# Page with Simple.Aspx using server-side Controls</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:BulletedList ID="DisplayList" runat="server">
    <asp:ListItem>Tahir's List with Server control  Item1</asp:ListItem>
    <asp:ListItem>Tahir's List with Server control  Item2</asp:ListItem>
    <asp:ListItem>Tahir's List with Server control  Item3</asp:ListItem>
    <asp:ListItem>Tahir's List with Server control  Item4</asp:ListItem>
    <asp:ListItem>Tahir's List  with Server control Item5</asp:ListItem>
    </asp:BulletedList>
    <h2 runat="server" id="tahirHeading">Total Number of Item=xx</h2>
    </form>
</body>
</html>

First a very Simple Page in Asp.net using List Control to display Item Dynamically


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SimpleWebSite._Default" %>

<script runat="server">
const int ItemCount=10;
String GetDisplayItem(int n){

return "TahirListItem#"+n.ToString();
}  
</script>

<!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>Tahir Khalid Simple Asp.net in C# Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <ul>
    <% for(int i=0; i<ItemCount;i++ ){ %>
    <li><%=GetDisplayItem(i) %></li>
    <%}%>
    </ul>
    </div>
    <%Response.Write("<h3>Total Number is the Tahir List=" + ItemCount.ToString() + "</h3>"); %>
    </form>
</body>
</html>

Friday 9 December 2011

Asp.net GriView Control and Asp.net SqlDataSourec Control used with Delete and Insert Options


<body>
    <form id="form1" runat="server">
    <div>
     <asp:GridView ID="TahirGrid" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" DataKeyNames="pk"
            DataSourceID="TahirDataSource"
            EmptyDataText="There are no data records to display.">
         
   <Columns>
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="Job_Title"    HeaderText="Job_Title"  SortExpression="Job_Title" />
                <asp:BoundField DataField="Job_Description" HeaderText="Job_Description"   SortExpression="Job_Description"  />
<asp:BoundField DataField="Experience_Required" HeaderText="Exprience_Required"   SortExpression="Exprience_Required"  />
<asp:BoundField DataField="Skills_Required" HeaderText="Skills_Required"   SortExpression="Skills_Required"  />
<asp:BoundField DataField="pk" HeaderText="ppk"   SortExpression="ppk"  />
    </Columns>

        </asp:GridView>
       
        <asp:SqlDataSource ID="ExencoDataSource" runat="server"
         ConnectionString="server=mssql2008-1;database=salmanexenco_2;user id=tahir; password=khalid"

            DeleteCommand="DELETE FROM [JobTable] WHERE [pk]=@pk"
            InsertCommand="INSERT INTO [JobTable] ([Job_Title],[Job_Description], [Experience_Required],[Skills_Required],[pk]) VALUES (@Job_Title,@Job_Description, @Experience_Required,@Skills_Required,@pk)"
            SelectCommand="SELECT [Job_Title],[Job_Description],[Experience_Required],[Skills_Required],[pk] FROM [JobTable]"
            UpdateCommand="UPDATE [JobTable] SET [Job_Title]=@Job_Title,[Job_Description]=@Job_Description,[Experience_Required]=@Experience_Required,[Skills_Required]=@Skills_Required WHERE [pk] = @pk">
            <InsertParameters>
                <asp:Parameter Name="Job_Title" Type="String"  />
                <asp:Parameter Name="Job_Description" Type="String"/>
<asp:Parameter Name="Experience_Required" Type="String"  />
                <asp:Parameter Name="Skills_Required" Type="String"/>
<asp:Parameter Name="pk" Type="Int32"/>
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="Job_Title" Type="String"  />
                <asp:Parameter Name="Job_Description" Type="String"/>
<asp:Parameter Name="Experience_Required" Type="String"  />
                <asp:Parameter Name="Skills_Required" Type="String"/>
<asp:Parameter Name="pk" Type="Int32" />
            </UpdateParameters>
            <DeleteParameters>
                <asp:Parameter Name="pk" Type="Int32" />
            </DeleteParameters>
        </asp:SqlDataSource>
   
    </div>
    </form>
</body>

Asp.net GriView Control and Asp.net SqlDataSourec Control used to display records from Database


  <div align="center">
      <asp:GridView ID="ExencoGrid" runat="server" AllowPaging="True" AllowSorting="True"
     AutoGenerateColumns="False" DataKeyNames="pk"
     DataSourceID="ExencoDataSource"
     EmptyDataText="Currently No Jobs are available.">
   
         
<Columns>
    <asp:CommandField ShowDeleteButton="false" ShowEditButton="false" />
<asp:BoundField DataField="Job_Title"    HeaderText="Job_Title"  SortExpression="Job_Title" />
    <asp:BoundField DataField="Job_Description" HeaderText="Job_Description"   SortExpression="Job_Description"  />
<asp:BoundField DataField="Experience_Required" HeaderText="Exprience_Required"   SortExpression="Exprience_Required"  />
<asp:BoundField DataField="Skills_Required" HeaderText="Skills_Required"   SortExpression="Skills_Required"  />
<asp:BoundField DataField="pk" HeaderText="ppk"   SortExpression="ppk"  />
</Columns>

  </asp:GridView>
       
  <asp:SqlDataSource ID="ExencoDataSource" runat="server"
   ConnectionString="server=mssql2008-1;database=Tahir_2;user id=tahir; password=khalid"
  SelectCommand="SELECT [Job_Title],[Job_Description],[Experience_Required],[Skills_Required],[pk] FROM [JobTable]"          >
 </asp:SqlDataSource>
   
    </div>

Thursday 8 December 2011

Code for Creating Connection with SQLSERVER 2008 using Csharpe

//Connection – used to connect to the data source
SqlConnection use = new SqlConnection(" Data Source=FAISALN;Initial Catalog=test;Integrated Security=True ");

 //DataAdapter use to populate the dataset  with data from the DataSource
            SqlDataAdapter da = new SqlDataAdapter();

//Command– used to execute a command against the data source and retrieve a DataReader or DataSet, or to execute an              INSERT, UPDATE, or DELETE command against the data source

 da.InsertCommand = new SqlCommand("insert into Username values (@Username, @Password)", use);
da.InsertCommand.Parameters.Add("@username", SqlDbType.NVarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("@password", SqlDbType.NVarChar).Value = textBox2.Text;
          
use.Open();
da.InsertCommand.ExecuteNonQuery();
use.Close();
//Clear the textboxes
            textBox1.Text = "";
            textBox2.Text = "";

ADO.NET DATABase Classes

Data Provider Components
Each .NET data provider consists of four main components:
   Connection – used to connect to the data source

   Command– used to execute a command against the data source and retrieve a DataReader or DataSet, or to execute an              INSERT, UPDATE, or DELETE command against the data source

  DataReader–A  forward-only, read-only connected resultset

   DataAdapter – used to populate a DataSet with data from the data source, and to update the data Source     

Saturday 3 December 2011

What is a Storeprocedure

STORE PROCEDURE:-A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again.  So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.
In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.

Example for Creating a Storeprocedure:-
CREATE PROCEDURE GetAddress
AS
SELECT * FROM AdventureWorks.Person.Address
GO

To execute the procedure call the statement
EXEC  GetAddress

What is an index and a view in DATA Base Theory

Introduction to index
Index:- is created for query optimization,on the column of a table so that the split record of the table is clustered with an index, having a key and values concept.
Extents: SQL server stores the row of table in data pages. 8 physical adjacent data pages are called extent.
Clustered Index:  rearrange the data in sequence manner.
Non clustered index: the data is not physically rearranged in sequential manner.
Heap: a table that does not have a clustered index.
IAM (Index Allocation Map): pages are used to keep track of what an extent is being used for.
Allocation units: is used to view information about table index.
Views
Definition of View
View is a dynamic, virtual table computed or collated from data in the database.
Or
 View is a virtual table.It doesn't occupy the memory in physical memory. So if we make any changes
it wont be reflect on original table.Views are mainly for providing security
Partitioned view: joins the data of tables from 1 or more servers (computer). :OR A partitioned view merges the data from the member tables, such that resultant data appear as it taken from a single table.
<!Partition view is created using union operator.
<!Create view employees
AS 
 Select * from employees_Lahore
Union ALL
Select * from employees_islamabad
Union ALL
Select * from employees_Rawalpindi

Distributed Partitioned View: Can be updated only if the user has Control, Alter or view definition permissions on each of the member tables.
Guideline to Create a View:
a)   A View is created only in the current database.
b)  View must have a unique name not same as the table names in the schema (DB Definition).
c)   A view cannot have a full-text index.
d)  A view definition cannot contain compute, compute by and into keywords.
<!Object_Definition : function can be used to display the view definition by providing the object id of the view as input parameter . For example      Select  OBJECT_DEFINITION(Object_ID(‘vEmp’))


Friday 2 December 2011

Simple Programe in C Sharpe ASP.net Langugage for the Concept of Inheritance


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TahirKhalid
{
    class Program
    {
        static void Main(string[] args)
        {
            //Human h = new Human();
            //h.eating();

            Employee e = new Employee();
            e.eating(); // where eating is function

            Console.ReadLine();
            }


        public class Human {
            public string eye;
            public string color;
            public string apperance;

            public void eating() {
                Console.WriteLine("i eat food");
            }

            public void speaking()
            {
                Console.WriteLine("i speak");
            }
           
       
        } //end Human class

        public class Employee:Human {

            public int salary;
            public string grade;


            public void calsalary() { salary = 2500;
            Console.WriteLine(salary);
            }
            public void calgrade() { grade = "manager"; }

       
        }
    }
}

Monday 28 November 2011

Form in HTML for the Validation


<form id="text_form" method="" action="">
<table id= "Table_01" width="100%" class="contactformlarge">
<tr>
<td align="right" valign="top" class="required">Name*</td>
<td align="left" valign="top"><input type="text" name="Name" id="Name" value="" size="25" maxlength="128" /></td>
</tr>
<tr>
<td align="right" valign="top" class="required">Email*</td>
<td align="left" valign="top"><input type="text" name="Email" onblur="echeck(Email.value)"id="Email" value="" size="25" maxlength="128" /> </td>
</tr>
<tr>
<td align="right" valign="top" class="required">Phone</td>
<td align="left" valign="top"><input type="text" name="Phone" id="Phone" value="" size="25" maxlength="128" />(Optional)</td>
</tr>
<tr>
<td align="right" valign="top" class="required">Country*</td>
<td align="left" valign="top"><input type="text" name="Country" id="Country" value="" size="25" maxlength="128" /> </td>
</tr>
<tr>
<td align="right" valign="top" class="required">Message*</td>
<td align="left" valign="top"><textarea name="Message" cols="35" rows="5" id="Message"></textarea> </td>
</tr>
<tr>
<td> </td>
<td><input id="smitbtn" type="Button" value="Submit Form" onclick="return( Blank_TextField_Validator() && callAjax(this));" /> </td>
</tr>
<tr>
<td>&nbsp;</td>
<td>*fields Compulsory </td>
</tr>
</table>
</form>

Checking the Form with Help of JS Script


function Blank_TextField_Validator()
{
//get the referece for form name text_formCheck the value of the element named text_name
// from the form named text_form
var x=document.getElementById("text_form");
for(var i=0;i<=5;i++)
{
if(i==2){
i=3;
}
if(x.elements[i].value=="")
{
// If null display and alert box
alert("Please fill in the text field.");
// Place the cursor on the field for revision
x.elements[i].focus();
//return false to stop further processing
return (false);
}
}//end loop
// If text_name is not null continue processing
return (true);
}
function echeck(str) {
var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(at,(lat+1))!=-1){
alert("Invalid E-mail ID")
return false
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(dot,(lat+2))==-1){
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1){
alert("Invalid E-mail ID")
return false
}
return true

Wednesday 23 November 2011

Adding HTML Tags Dynamically and Styling them with help of JavaScript

<html>
<head>
<script type="text/javascript">

function loadDoc()
{
var newelement=document.createElement("P");
document.body.appendChild(newelement);
newelement.appendChild(document.createTextNode("HellowWorld"));

var divElement=document.createElement("DIV");
divElement.style.width="100px";
divElement.style.height="100px";
divElement.style.backgroundColor="RED";
//divElement.style.styleFloat="left";   //for I.e property is styleFloat
divElement.style.cssFloat="left";       // for other browsers  property is cssFloat 
document.body.appendChild(divElement);  
                                           

}
</script>
</head>
<body>

<div id="myDiv" style=" width:100px; height:100px;">I am in HTML File  </div>
<p>This Script is written by Tahir Khalid ALL Right Reversed</p>
<input  type="button" onClick="loadDoc()" />

</body>
</html>

Tuesday 22 November 2011

Using Ajax Comparsion Two Div and Select Tag

<html>
<head>
<title>Comparison</title>


<script type="text/javascript">
 function  showPage1(str){
 var xmlhttp;   
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET"," "+str+" ",true);

xmlhttp.send();

 }



 function  showPage2(str){
 var xmlhttp;   
if (str=="")
  {
  document.getElementById("txtHint2").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET"," "+str+" ",true);

xmlhttp.send();

 }


</script>


 <div class="column1-unit" style="width:655px">
       
        <div style="width:315px; float:left">
         <select id="ourSelect" onChange="showPage1(this.value)"  style="width:150px;" >
        <option >Select a Model</option>
       <option value="HondaAccord.html" >Honda Accord</option>
       <option value="HondaCity.html">Honda City</option>
       <option value="HondaCivic.html">Honda Civic</option>
      <option value="HondaCRV.html">Honda CR-V</option>
      <option value="Mahran.html">Mahran</option>
              <option value="Cultus.html">Cultus</option>
              <option value="Swift.html">Swift</option>
              <option value="Prado.html">Prado</option>
              <option value="GLI.html">GLi</option>
              <option value="XLI.html">XLi</option>
            </select>
          </div><!--closing of select div-->
         
       
              
        <div style="width:315px; float:left">
          <div align="center">
           <select id="ourSelect" onChange="showPage2(this.value)"  style="width:150px;" >
              <option selected="selected">Select a Model</option>
              <option value="HondaAccord.html" >Honda Accord</option>
       <option value="HondaCity.html">Honda City</option>
       <option value="HondaCivic.html">Honda Civic</option>
      <option value="HondaCRV.html">Honda CR-V</option>
      <option value="Mahran.html">Mahran</option>
              <option value="Cultus.html">Cultus</option>
              <option value="Swift.html">Swift</option>
              <option value="Prado.html">Prado</option>
              <option value="GLI.html">GLi</option>
              <option value="XLI.html">XLi</option>
              <option value="ToyotaCamry.html">Camry</option>
            </select>
          </div>
         
         

         
         
        </div>
        <div id="txtHint" Style="width:315px;  height:315px; float:left; overflow:scroll; "   >Customer info will be listed here...</div>
<div id="txtHint2" Style="width:325px;  height:315px; float:left; margin-left:10px; overflow:scroll;" >Customer info will be listed here...</div>
       
           <!--/header-->
        
        </div>
                                                                     

    
</body>
</html>

Loading and Passing Images and Text values to JavaScript Function Dynamically

<html>
<head>
<script type="text/javascript">
function loadDoc(disimg)
{
alert(disimg);
document.write(disimg);
document.write("<p>"+disimg+"</p>");
document.getElementById("myDiv").innerHTML="<p>"+disimg+"</p>";
document.getElementById("myDiv").innerHTML="<img src="+disimg+".jpg"+"/>";
}

function loadDoc2(disimg)
{
alert(disimg);
document.getElementById("myDiv").innerHTML="<img src="+disimg+".jpg"+"/>";
}

</script>
</head>
<body>
<div id="myDiv" style=" width:400px; height:400px;"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc('cat')">Change Content</button>
<button type="button" onclick="loadDoc2('cat')">ChangeImage</button>
</body>
</html>

JavaScript for Fliping images

<html>
<head>
<script type="text/javascript">
var image1=new Image()
image1.src="images/Gas_Final.jpg"
var image2=new Image()
image2.src="images/Chemical_Plant1_Final.jpg"
var image3=new Image()
image3.src="images/Chemical_Plant2_Final.jpg"
//variable that will increment through the images
var step=1
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.images.slide.src=eval("image"+step+".src")
if (step<3)
step++
else
step=1
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit()
</script>
</head>
<body onload="slideit()">
<div class="banner_box"><img src="images/banner.jpg"  name="slide" alt="">
</div>
</body>
</html>

Wednesday 28 September 2011

Meta Tag

<meta name="keywords" content="Exenco,Expert Engineering Company,Industrial automation,Control System Solutions,,mechanical,Electrial,Instrumentation and Control SCADA,PLC,DCS,HMI Turnkey Projects, Brownfield Projects, Green Field projects, O&M Services, Opration Maintenance services, Site services"/>


<meta name="description" content="Exenco The Engineering Company for Industrial Automation and Engineering Solutions and services" />

HTML Anchor Tag

<html>
<head>
<title>.:: Best Stories online ::. - BestStory.com</title>
</head>
<body>
<h1 align="center">Best Stories Online</h1>
<h2><marquee>www.beststory.com</marquee></h2>
<p>We have best stories for you. Please read...</p>
<h2><a name="topstory1">Story 1</a> :</h2>
<p>Once upon a time there was a king...
Once upon a time there was a king...
<a href="#story1">Read More</a></p>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
<h5><a name="story1"> Remaining Part Of Story 1 :</a></h5>
<p>He was very kind and best king. But he had no child</p>
<p><a href="#topstory1">Click here</a> to go on top of story 1.</p>

</body>

</html>

Tuesday 20 September 2011

Graphics Using ball


import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
public class hellokid extends Frame{
int x=50;
int y=50;
int dx=1;
int dy=1;
public hellokid() {
setSize(800,600);
setVisible(true);
}@Override
public void paint (Graphics g) {
g.setColor(Color.black);
g.drawOval(x,y,200,200);
g.fillOval(x,y, 200,200);
super.paint(g);
x=x+dx;
y=y+dy;
if(x==500 && y==500){
x=50;y=50;
dx=1;
dy=1;

repaint();
}


repaint();
for(int a=1;a<20000000;a++){}
}
public static void main (String arg[])
{
hellokid w=new hellokid();
}
}

Interface using GUI Component in java for Database application


import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Student{
Frame f=new Frame("student");
Panel p;
JLabel l,l1,l2,l3;
JTextField t,t1,t2,t3;
JButton b,b1,b2,b3,b4;//insert,update,record,find,delete
public Student(){

f.setLayout(null);

l=new JLabel("Roll No.");

l.setLayout(null);

l1=new JLabel("Student Name");
l1.setLayout(null);
l2=new JLabel("Address");
l2.setLayout(null);
l3=new JLabel("Course");
l3.setLayout(null);
l.setLocation(60,50);
l.setSize(60,20);
t=new JTextField();
t.setLocation(120,50);
t.setSize(100,20);
l1.setLocation(270,50);
l1.setSize(80,20);
t1=new JTextField();
t1.setLocation(380,50);
t1.setSize(100,20);


l2.setLocation(60,90);
l2.setSize(60,20);
t2=new JTextField();
t2.setLocation(120,90);
t2.setSize(100,20);



l3.setLocation(270,90);
l3.setSize(80,20);
t3=new JTextField();
t3.setLocation(380,90);
t3.setSize(100,20);


p=new Panel();
p.setLayout(null);
p.setLocation(0,170);
p.setSize(1024,70);
p.setBackground(Color.gray);



b=new JButton("add");
b.setLayout(null);
b.setLocation(50,10);
b.setSize(70,30);
b.setForeground(Color.blue);



b1=new JButton("update");
b1.setLayout(null);
b1.setLocation(130,10);
b1.setSize(90,30);
b1.setForeground(Color.blue);




b2=new JButton("search");
b2.setLayout(null);
b2.setLocation(230,10);
b2.setSize(100,30);
b2.setForeground(Color.blue);




b3=new JButton("delete");
b3.setLayout(null);
b3.setLocation(340,10);
b3.setSize(100,30);
b3.setForeground(Color.blue);


p.add(b);
p.add(b1);

p.add(b2);

p.add(b3);
f.add(l);
f.add(t);

f.add(l1);
f.add(t1);


f.add(l2);
f.add(t2);

f.add(l3);
f.add(t3);
f.add(p);





f.setSize(800,800);
f.setVisible(true);


}//end of constructor

public static void main(String m[]){
new Student();

}//end of main
}//end of class

Monday 19 September 2011

how to connect with jdbc,odbc with access


import java.sql.*;
public class Test1
{
 public static void main(String[] args)
 {
 try {
int rollno=240;
String name="Tahir";
String address="Lahore";
String course="Java";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:StudentDB");
Statement s = con.createStatement();
s.executeUpdate("insert into StudentTable(RollNo,StudentName,StudentAddress,StudentCourse)

values("+rollno+",'"+name+"','"+address+"','"+course+"')");


s.close();
con.close();   }
catch (Exception err) {
System.out.println("ERROR: " + err);
 }
 }
}    

Friday 16 September 2011

How to write in a File and Read from a File in Java



import java.io.*;
public class FileWriter{

public FileWriter(){

try{
FileOutputStream fos =new FileOutputStream("data.txt");
BufferedOutputStream bos= new BufferedOutputStream(fos);
DataOutputStream dos= new DataOutputStream(bos);


dos.writeUTF("Testing the file program");


dos.close();
fos.close();


FileInputStream fis =new FileInputStream("data.txt");
BufferedInputStream bis= new BufferedInputStream(fis);
DataInputStream dis= new DataInputStream(bis);
String s=dis.readUTF();
System.out.println(s);

dis.close();
fis.close();
}catch(Exception e){}


}//end of constrctr

public static void main(String m[]){

new FileWriter();



}//end of main
}//end of class

How to get Input in Java


import java.io.*;

public class GetUserInput {
    public static void main (String[] args) {
       System.out.print("Enter your name and press Enter:

");
       BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));
       String name = null;
       try {
         name = br.readLine();
       } catch (IOException e) {
         System.out.println("Error!");
         System.exit(1);
       }
       System.out.println("Your name is " + name);
}
}

Tuesday 23 August 2011

Thread (Two Threads working to gather)

public class MyThread1 extends Thread{

  MyThread1(String name){
        super(name);

         }

public void run(){

for(int i=1; i<=15; i++){
System.out.println("I am "+getName()+i);
        try{
       Thread.sleep(1000);
   }catch(Exception e){}
                    }
System.out.println("I Finished"+getName());



}


 public static void main(String agr[]){
          MyThread1  mt1=new MyThread1("Thread1");
          mt1.start();  
          MyThread1  mt2=new MyThread1("Thread2");
          mt2.start();  
 

      

 }

}

Friday 19 August 2011

Exception Handling in Java

public class MyException{

public void myFun() {
int[] array = new int[3];
  try{

 for(int i=0;i<4;++i){
  array[i] = i;
  }
 System.out.println(array);
  }catch(ArrayIndexOutOfBoundsException e){
   //printed just to inform that we have entered the catch block
                       System.out.println(e.toString()+"\n");
   //System.out.println("Oops, we went to far, better go back to 0!");
  }
 }


 public static void main(String Args[]){
 MyException me=  new  MyException();
   try{
   me.myFun();
                        me.myMethod();

  }catch(Exception e){System.out.println(e.toString()+"\n");}

        }

public void  myMethod() throws ArithmeticException{
     throw new ArithmeticException();
}


}