-->

Saturday, February 1, 2014

Concept of Memory Allocation in C Programming


As the stored program concept specifies, the data and instructions that are to be processed should be stored in main memory of the computer, the memory allocation comes into picture. The data that is to be processed must be stored in main memory so that is readily available to the processor and can fetched and stores in internal registers for processing. Reserving space in main memory for the data variables and used for storing data in it later through assignment or input is called as memory allocation. So once the data structure is decided and variables are declared in the declaration part of the program (in case of C language) memory is allocated to the variables of the respective data structured by the compiler. This is called as memory allocation. For example, consider the following C program:-
           void main()
          {
            int a, b, c;
            . . . . .
         }
When the above  program is compiled memory of two bytes each is allocated to the variables a, b and c respectively. These memory locations are used to store two bytes signed integers (data). In the program the data are referred through variables names (identifiers). Consider another example,
         void main()
          {
            int arr[20];
            . . . . .
         }

When this program is compiled 40 bytes of consecutive memory is allocated to store 20 integers and all the integers are referred by a single variable “arr” with the proper index.
         void main()
          {
            int *arr; int size=20;
            arr= (int *) malloc (2 * size);
         }
When the above program is executed 40 bytes of memory is allocated during execution and the base address is stored in a pointer variable arr. With the help of arr now it is possible to refer 20 integers.
           The above mentioned all examples explain basic concept of memory allocation.



Delete Element from Array in PHP Programming


Delete  element in PHP array:-  If we wish to delete an item or element from PHP array then we have three choices first is remove the element  from starting position ,second is remove the elements  from last position and third is remove the element at any desire position of an array. Here following code is showing that how to implement above three operations.

Remove the element from starting position: - This can be possible to use  array_shift() PHP function. Syntax of this method is follows:-

mixed array_shift(array array);
this can be understood with the help of following code.
Let we  have an array 
$name =array(“weilems”, “jon”,”jacob”);

If we want  to remove the first name from this array then we can use array_shift() function such that
 Array_shift($name);
After execute this statement the start index value of this array is removed and the index of next elements is decremented by 1 this can be use for associative array.

Remove the element from ending position: - This can be possible to use array_pop() PHP function. Syntax of this method is follows:-

mixed array_pop(array target_array) 
this can be understood with the help of following code.
Let we  have an array 
$name =array(“jack”,“jon”,”jackren”);

If we want  to remove the last name from this array then we can use array_pop() function such that
 Array_pop($name);
After execute this statement the last index value of this array is removed. And the array becomes $name =array(“jack”,“jon”);

Remove the element at any desire position:- This is possible by using PHP unset() method. The syntax of this method is follows:-

unset(mixed vriable);
for example let we have an array such that
$branch=array(“CS”,”IT”,EE”);

And we want to remeove IT branch from this array then we can use unset() function in following way.
Unset ($branch [1]);
After execute this statement value stored at first index of array $branch will be unset and removed.

Friday, January 31, 2014

DropdownList SelectedIndexChanged page reload but value not change

Introduction 

If you want to bind one DropdownList from another DropdownList. But you notice that your first DropdownList take same result, After PostBack your page will refreshed, again Page_Load function will be run.

The reason behind

Because your first Dropdownlist bind on Page_Load Event  with both postback and without postback mode.

Solution of the problem is 

 Bind first DropDownList on Page_Load event with withoutPostBack mode.

Lets take an simple example to demonstrate it

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>
    Select Country
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
            Height="52px" onselectedindexchanged="DropDownList1_SelectedIndexChanged" 
            Width="279px">
        </asp:DropDownList>
        <br />
        <br />
        Select state
        <asp:DropDownList ID="DropDownList2" runat="server" Height="33px" Width="299px" 
            Visible="False">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack )
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Select * from country";
            cmd.Connection = con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DropDownList1.DataSource = ds;
            DropDownList1.DataTextField = "countryname";
            DropDownList1.DataValueField = "countryid";
           
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, "select any country");
            con.Close();
            
        }
        

        
       
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList2.Visible = true;

        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select * from state where countryid='"+DropDownList1 .SelectedValue+"'";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DropDownList2.DataSource = ds;
        DropDownList2.DataTextField = "statename";
        DropDownList2.DataValueField = "Stateid";
        DropDownList2.DataBind();
        con.Close();

    }

}

Code Generate the following output
DropdownList SelectedIndexChanged page reload but value not change

How to Querying Data using Joins in Sql Programming: Part 4

Equi Join

In SQL programming, an Equi join is the same as an inner join and joins tables with the help of a foreign key. However, an equi join is used to display all the columns from both the tables. The common column from all the joining tables is displayed.

Consider an example where you apply an equi join between the EmployeeDepartmentHistory, Employee, and Department tables by using a common column, BusinessEntityID. To perform this task, you can use the following query:

SELECT * FROM HumanResources.EmployeeDepartmentHistory d
JOIN HumanResources.Employee e ON d.BusinessEntityID = e.BusinessEntityID
JOIN HumanResources.Department p ON p.DepartmentID = d.DepartmentID

The output of this query displays the EmployeeID column from all the tables, as shown in the following figure.

Equi join sql programming

Self Join

In a self-join, a table is joined with itself. As a result, one row in a table correlates with other rows in the same table. In a self-join, a table name is used twice in the query. Therefore, to differentiate the two instances of a single table, the table is given two alias names.

The following example performs a self-join of the Sales.SalesPerson table to produce a list of all the territories and the sales people working in them.

SELECT st.Name AS TerritoryName, sp.BusinessEntityID, sp.SalesQuota, sp.SalesYTD
FROM Sales.SalesPerson AS sp JOIN Sales.SalesTerritory AS st
ON sp.TerritoryID = st.TerritoryID
ORDER BY st.Name, sp.BusinessEntityID

The output of the self-join is shown in the following figure.

Self join sql programming


How to Querying Data using Joins in Sql Programming: Part 3

A cross join, also known as Cartesian Product in SQL programming, between two tables joins each row from one table with each row of the other table. The number of rows in the result set is the number of rows in the first table multiplied by the number of rows in the second table.

This implies that if Table A has 10 rows and Table B has 5 rows, then all 10 rows of Table A are joined with all 5 rows of Table B. therefore, the result set will contain 50 rows.

Consider following query in which all the BusinessEntityID is retrieved from SalesPerson table and SalesTerritory with their cross join. The where condition will filter the result according to the territoryID, and at the last the result will sort by the resulting BusinessEntityID.

SELECT p.BusinessEntityID, t.Name AS Territory
FROM Sales.SalesPerson p
CROSS JOIN Sales.SalesTerritory t
WHERE p.TerritoryID = t.TerritoryID
ORDER BY p.BusinessEntityID

The preceding query combines the records of both the tables to display the result with all the possible combinations, as shown in the following figure.

How to Querying Data using Cross Joins in Sql Programming


Item selection required for ListBox in ASP.NET

If you want to do it in asp.net that your website visitor select any one option in given ListBox item. Use Required Field Validator for this type of problem, also set initial value. If your initial value is match with your selected item, error message generated on client machine. lets do it in asp.net with sort code example

Selection is required 

<%@ Page Language="C#" %>

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

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <strong>Selection Required<br />
        </strong>
    </div>
        <asp:ListBox ID="ListBox1" runat="server" Height="132px" Width="147px">
            <asp:ListItem>Select Control</asp:ListItem>
            <asp:ListItem>Button Control</asp:ListItem>
            <asp:ListItem>Calendar Control</asp:ListItem>
            <asp:ListItem>CheckBox Control</asp:ListItem>
            <asp:ListItem>FileUpload Control</asp:ListItem>
    </asp:ListBox>
    &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
        ControlToValidate="ListBox1" ForeColor="Red" InitialValue="Select Control">Please Select Control</asp:RequiredFieldValidator>
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Submit" />
    </form>
</body>
</html>

Code Generate the following output

Item selection required for ListBox in ASP.NET

Bind DetailsView with insert, edit and delete in ASP.NET

You can easily bind your DetailsView data control in asp.net using SqlDataSource, SqlDataSource provides connectivity between front end to back-end with all insert, edit and delete features. This example covers that how to bind your DetailsView with database. These are following steps

Step-1 : Create a SQL Table with some fields like
sno int (primaryKey, Isidentity=true)
name nvarchar(50)
address nvarchar(250)


Step-2 : Add SqlDataSource Control to Design window from toolbox
Step-3 : Select 'Configure Data Source' link using show Smart tag.

'Configure Data Source'



Step-4 : Select Database or ConnectionString from Dropdown menu.
ConnectionString

Step-5 : Select Table-name from Dropdown menu also select Advanced tab.
Table-name from Dropdown menuAdvanced tab

Step-6 : Select Insert, Update and delete checkbox option.
Step-7 : Click to Test Query and  Finish button.

Step-8 : Add DetailsView Control to the page, check all insert, update, and delete features using show smart teg.
Bind DetailsView with insert, edit and delete in ASP.NET

Now generate source code in page file

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!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>
    
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            DeleteCommand="DELETE FROM [emp] WHERE [sno] = @sno" 
            InsertCommand="INSERT INTO [emp] ([name], [address]) VALUES (@name, @address)" 
            SelectCommand="SELECT * FROM [emp]" 
            UpdateCommand="UPDATE [emp] SET [name] = @name, [address] = @address WHERE [sno] = @sno">
            <DeleteParameters>
                <asp:Parameter Name="sno" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="name" Type="String" />
                <asp:Parameter Name="address" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="name" Type="String" />
                <asp:Parameter Name="address" Type="String" />
                <asp:Parameter Name="sno" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
    
    </div>
    <asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" 
        AutoGenerateRows="False" DataKeyNames="sno" DataSourceID="SqlDataSource1" 
        Height="50px" Width="125px">
        <Fields>
            <asp:BoundField DataField="sno" HeaderText="sno" InsertVisible="False" 
                ReadOnly="True" SortExpression="sno" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
            <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" 
                ShowInsertButton="True" />
        </Fields>
    </asp:DetailsView>
    </form>
</body>
</html>

Code Generate the following output

Bind DetailsView with insert, edit and delete in ASP.NET

© Copyright 2013 Computer Programming | All Right Reserved