-->

Saturday, February 7, 2015

Linked List in Data Structures through C language

Linked List

Linked List is linear and dynamic data structure. The list is a collection of elements called nodes and each node is created dynamically. Linked List comes into picture to overcome the disadvantages of Array. In array it is not possible to vary the size. The size is fixed and the memory is allocated statically when it is declared. During the compilation time the memory is allocated to array. In case of linked list memory is allocated at the time of execution, so the size can vary according to the user wish. In case of Linked List only linear search is possible and it is difficult to apply sorting.

          Each node in the linked list consists of two parts. One part is called as INFO(information) part and the other part is called LINK or NEXT (pointer to next node) part. The INFO part contains the information about the element which is same type for all the nodes and the link part contains address or location of the next element in the List. As one element is linked with the other element, so the list is called as Linked List. The address of the first node of the linked list is stored in an external pointer called ROOT or FIRST.


                                                                                              NODE


  Graphical representation of Linked List  



               
                                               
         ROOT contains the address of the first node FIRST, FIRST node ‘s link field contains the address of the second node SECOND, SECOND node’s link filed contains the address of the third node THIRD and THIRD node’s link field contains the address of the fourth  node FOURTH. Fourth node the last node’s link field of the list contains a NULL address to specify the end of the list. In this case NULL address is marked with X (cross). In some representations it is marked to point to ground symbol.


Friday, February 6, 2015

Gridview sorting Example in ASP.NET

Introduction

Sorting means arranging your data either in ascending order or descending order. But, why we do perform sorting between data? The answer is to increase the speed of readability. So, we need sorted data. Various types of sorting Technique is available like merge sort, quick sort, bubble sort, selection sort, insertion sort and etc. Here, I perform sorting in the GridView. Actually this control provide built in sorting functionality so no code is required for it. But, I will give you example of sorting by using code behind file. Sorting and sorted event of this control provide you to customize the sort functionality like you can use either ViewState or other technique.  First of all I would like to talk about inbuilt functionality which is provide by this control. Let see the example

Step-1 : Create a DataBase table in Visual Studio
Step-2 : Bind GridView with SqlDataSource control
Step-3 : Select 'Enable Sorting' CheckBox for sorting.
Gridview sorting in ASP.NET

Code generate the following output

Gridview sorting Example in ASP.NET

Gridview sorting Example in ASP.NET

Complete Source Code with AllowSorting="True" property

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

<!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">
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
            AutoGenerateColumns="False" DataKeyNames="sno" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="sno" HeaderText="sno" ReadOnly="True" 
                    SortExpression="sno" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Address" HeaderText="Address" 
                    SortExpression="Address" />
            </Columns>
        </asp:GridView>  
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            SelectCommand="SELECT * FROM [userdata]"></asp:SqlDataSource>
    </div>
    </form>
</body>
</html>
If you bind the GridView control with the SqlDataSource. GridView provide functionality to sort the column without any coding. With the help of allowSorting property of this control you can make column as linkButon, i mean to say LinkButton controls displayed at the top of each column of the grid lets see the output of the above mentioned program. Now to the second part that is sorting through code behind file:

II Method (Sorting through Code Behind file)

Here, i will use ViewState, SortDirection and SortExpression for sorting. With the help of SortDirection enumeration we can retrieve sort order of the column. Also access the last state information of Post Back event by using ViewState. Let see the example

  1. First to add the GridView control to the design page.
  2. Bind this control with the DataTable.
  3. Copy this code and paste into your code behind file

    private void bindgridview()
    {
        var data = getDataTable();
        GridView1.DataSource = data;
        GridView1.DataBind();

    }

    private DataTable getDataTable()
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString=ConfigurationManager.ConnectionStrings["btti"].ToString();
        con.Open();
        SqlCommand cmd=new SqlCommand();
        cmd.CommandText = "select * from [register]";
        cmd.Connection=con;
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataSet ds=new DataSet();
        da.Fill(ds);
        return ds.Tables[0];

    }
  1. Now, perform Customization in the sorting by using GridView_Sorting event.
  2. Copy this code in the same code behind file.
  protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExp = e.SortExpression;
        string direction = string.Empty;
        if(SortDir==SortDirection.Ascending)
        {
            SortDir = SortDirection.Descending;
            direction = "DESC";
        }
        else
        {
            SortDir = SortDirection.Ascending;
            direction = "ASC";
        }
        DataTable dt = getDataTable();
        dt.DefaultView.Sort = sortExp +" " + direction;
        GridView1.DataSource = dt;
        GridView1.DataBind();



    }


    public SortDirection SortDir
    {
        get {
        if(ViewState["SortDir"]==null)
        {
            ViewState["SortDir"] = SortDirection.Ascending;
        }
        return (SortDirection)ViewState["SortDir"];
        
        }
        set {

            ViewState["SortDir"] = value;
        }
    } 
Here, SortDir is the public property through this we can access ViewState Information. When first time page is loaded ViewState contain null value so the sorted order is default ascending. So, SortDir key of it contain Descending order with the DESC string direction. When we click on any link button which is mentioned with the table column it rearrange the column according to SortExpression (table Column) and Direction.

Wednesday, February 4, 2015

Online GYM application project in ASP.NET

Admin Panel:

  • No need of admin registration form just provide username and password change option
  • Admin it self will register client details. So you have to provide client registration form for admin only(Need to provide insert, update and delete option for manipulating client details for admin except username and password)
Client Registration Form Details
1. Complete name
2. Email Id
3. Phone No
4. Date
5. Address
6. Height
7. Weight
8. Programs(Drop Down List)
When admin selects the type of program i.e cardio fitness, strengths, weight loss, personal trainer, cardio+strengths in another drop down list plans should populate
9. Plans      
 For example. Look at below video:

After Selecting Program and plan amount should display in text box.
1.       Paid Amount
2.       Amount Due=Plan amount-Paid Amount
3.       Upload Image
4.       Date(calendar)
5.        Registration button and Cancel Button 

Once registration is successful with all validations espically emailed and phone number. An email should send to that particular person with a welcome note along with username and password. Username as emailed and password as phone number.
Important Note: While client registration a Qrimage along with Unique qrcode and a excel sheet has to be generated. That excel sheet should contain the fallowing columns.

Sl.No, Name ,EmailId, Phone no, Emergency contact no, Address, Height, Weight, Selected Program, Selected Plan ,Amount paid, Due Amount  

When ever new client registration is successful the existing excel sheet should Update with a new row. QrImages  should be generated in separate folder with client name. Once admin will login he should be able to view his clients with respect to their programs. 

Example:
Select Type Of program:---Select----(Assume it’s a drop down list)
                                             Cardio
                                              Strength
                                             Personal Trainer
                                            Weight Loss
                                             Etc etc
Once admin click any of the above program i.e Strengths or cardio or weight loss or Personal trainer or any other register client should display w.r.to that program only.

Once admin select the client it should ask for edit profile option or display client info.

Tuesday, February 3, 2015

Computer Programming: How to insert data into excel file in ASP.NET, Example

This article will cover, How to insert data into Excel spreadsheet using ASP.NET. First we need to connect Microsoft Excel workbook using the OLEDB.NET data provider. Add excel file path to connectionString. Now, your connectionstring will be look like

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("first.xls") + ";" + "Extended Properties=Excel 4.0;";

Here, you can connect .xls file using Microsoft.Jet.OLEDB.4.0 provider also insert data in it. In Data Source, you can take .xls file path.

You can follow some steps for inserting data into excel file.

Step 1: Open Visual Studio > File > New >Website, Under Templates, click ASP.NET WebSite and choose Visual C# as the language. Select a system location and click Ok.

Step 2: We will create excel sheet and add them to the website folder. Excel sheet will be created in Office 2003(first.xls).

Step 3: Add three columns called id, name and Address to the Sheet1. Also add some data into the columns. Once this excel file is created, add it to your website folder. To add them to the solution, right click website name > Add Existing Item > Add the excel file.

Insert data into excel file using asp.net

Step 4: Add a web form called 'excelfile.aspx' into the website folder.
Step 5: Add a label control to the 'excelfile.aspx' page.
Step 6: Insert Data into excel file using OLEDB

Complete code is

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

<!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>
    </div>
    <asp:Label ID="Label1" runat="server"></asp:Label>
    </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.OleDb;
using System.Configuration;
using System.Data;

public partial class excelfile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("first.xls") + ";" + "Extended Properties=Excel 4.0;";

        OleDbConnection oledbconn = new OleDbConnection(connString);
        try
        {
            oledbconn.Open();
            OleDbCommand cmd = new OleDbCommand("insert into [Sheet1$] values('2','Jacob','USA')", oledbconn);

          int a=  cmd.ExecuteNonQuery();
          if (a>0)
          {

              Label1.Text = "Data Inserted";
          }

            
        }
        catch (OleDbException ex)
        {
           Label1.Text = ex.Message;
        }
        finally
        {
            oledbconn.Close();
        }
    

    }
}

Code generate following output

Data Inserted into excel file in asp.net
Data Inserted into excel file in asp.net

How to bind Gridview from two Merged Data Table

Introduction

It is a combination of DataColumns and DataRow. Generally, we use it for data binding purpose. In this article we will learn how to design the DataTable , merge two DataTable and Bind the gridview control with merged DataTable. First of all, create the object of it then add some column in it. After define the columns you will enter data in the columns. We have already dicussed on this topic earlier. Today, we will focus on merge( ) method.

Add columns and rows in the DataTable (Copy and Paste)


DataTable datatable1 = new DataTable();

        datatable1.Columns.Add("id", typeof(Int32));
        datatable1.Columns.Add("Name", typeof(string));
        datatable1.Rows.Add(1, "A");
        datatable1.Rows.Add(2, "B");

Above code define, we have two column that is, id with integer DataType and Name with string DataType. Similarly, we can design code for second DataTable. Like

  DataTable datatable2 = new DataTable();
        datatable2.Columns.Add("id", typeof(Int32));
        datatable2.Columns.Add("Name", typeof(string));
        datatable2.Rows.Add(3, "C");
        datatable2.Rows.Add(4, "D");

How to merge  DataTable:

After preparing the DataTable, you should use Merge( ) method. Like

datatable1.Merge(datatable2);

Now, you have to bind the GridView with Merged DataTable.

   GridView1.DataSource = datatable1;
        GridView1.DataBind();

Now code Generate the following output:

How to bind Gridview from two Merged Data Table

Sunday, February 1, 2015

How to find controls from usercontrols in ASP.NET

Introduction

Today, when we was design a program with the help of  web usercontrol. I was take two web usercontrols in the single web form (learn how to add web usercontrol in the aspx page) with a single button control. My code look like in the ASPX page:

    <uc1:Register ID="Register1" runat="server" /> 
        <uc2:login ID="login1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Find control" Width="483px" />

I want to access controls which is inside in user controls such as Button, TextBox, Label, Dropdownlist and etc. So, For this type of problem, i have a solution. Actually user control is a collection of controls or text and each control have a id property; also control have a runat attribute. So, easily we can access or find controls in the code file as well as in the <script> block. In this article i will explain you how to find the controls such as Button, Label, TextBox and etc from the user control

Find controls from user controls in the code file I-Method:

The Web User Control:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Register.ascx.cs" Inherits="MyControl_Register" %>

<asp:TextBox ID="usertxt" runat="server" Width="209px"></asp:TextBox>

The Page

The following HTML Markup of the ASPX Page contains the UserControl and a Button.
The button has an OnClick event handler which executes a click function which validates the TextBox usertxt present inside the UserControl Register.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>
<%@ Register src="MyControl/Register.ascx" tagname="Register" tagprefix="uc1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <uc1:Register ID="Register1" runat="server" />
    
    </div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Find control from user control" Width="483px" />
    </form>
</body>
</html>

Code Behind file

protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox t1 = Register1.FindControl("usertxt") as TextBox;
        if(t1.Text == "")
        {
            Response.Write("<script>alert('please fill the username')</script>");
        }
    }

Find controls from user controls using java script II-Method:

Also we can find the controls such as Label, ListBox, etc., which is inside in user controls. But a little problem you and i face that is:
When i place an toolBox controls inside usercontrols then the HTML ID of the control which is inside in usercontrol changes. And hence Java Script is not determine the control so, it is unable to find the control. Suppose, you have a TextBox with ID usertxt in a web user control, render web form in the browser and see the html source view :

 <input name="Register1$usertxt" type="text" id="Register1_usertxt" style="width:209px;" /> 

  Solution of the problem

Use Embedded code block with ClientID property in the document.getElementById menthod.
Now, Your whole code look like

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

<%@ Register src="MyControl/Register.ascx" tagname="Register" tagprefix="uc1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        function validate()
        {
            var t1 = document.getElementById('<%= Register1.FindControl("usertxt").ClientID %>');
            if (t1.value=="") {
                alert("Please fill username");
            }
        }


    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <uc1:Register ID="Register1" runat="server" />
    
    </div>
        <asp:Button ID="Button1" runat="server" Text="Find control using java script" Width="451px" OnClientClick="validate()" />
    </form>
</body>
</html>

If you want to see the full implementation and output, see this video:


Example programs showing pointer assignment, addition and subtractions in Data Structures through 'C'

Example programs showing pointer assignment, addition and subtractions:


1.’C’ program to read and print a dynamic array of the user required size:
   #include<stdio.h>
  #include<conio.h>
  #include<stdlib.h>
main(),
{
 int *arr, size, i;
 /* arr is a pointer to store address of dynamically allocated memory*/
 clrscr();
 printf(“Enter the size of array :”);
 scanf(“%d”,&size);
  arr=(int*)malloc(size*sizeof(int));
   /* dynamic memory allocation, pointer assignment operation */

  If(arr= = NULL)
 {
   printf(“Memory allocation error!”);
   exit(0);        /*to terminate program execution */
 }    /*end of if*/
 printf(“\n Enter array elements:”);
 for(i=0;i<size;i++)
    scanf(“%d”,arr+i);                                 /*pointer
addition */
  printf(“\nThe array is:\n”);
  for(i=0;i<size;i++)
  printf(“%d”,*(arr+i));                                  /*pointer
 addition */

}             /* end of main() */


NOTE: The array elements can also be referred as arr[i],
Where ’i’ is the index of the respective element.
The same program 1 for reading and displaying dynamic array can also be written with pointer subtraction as follows:

To read the array and display the array using pointer subtraction operation, the address of the last element is stored in a pointer variable and it is update accordingly by subtracting the respective index of the element to be read or displayed.
   #include<stdio.h>
  #include<conio.h>
  #include<stdlib.h>
main(),
{
  int *arr, size, i,*p;
  /* arr is a pointer to store address of dynamically allocated memory*/
  clrscr();
  printf(“Enter the size of array :”);
  scanf(“%d”,&size);

   arr=(int*)malloc(size*sizeof(int));
   /* dynamic memory allocation, pointer assignment operation */

   if(arr= = NULL)
   {
     printf(“Memory allocation error!”);
     exit(0);        /*to terminate program execution */
     }    /*end of if*/

  p=&a[size-1];/*address of the last element */
  printf(“\n Enter array elements:”);
  for(i=size-1;i>=0;i--)
   scanf(“%d”,p-i);                   /*pointer subtraction*/

  p=&a[size-1]; /*pointer assignment */
  printf(“\nThe array is:\n”);
  for(i=0;i<size;i++)
   printf(“%d”,*(p-i));      /*pointer subtraction*/

}             /* end of main() */

2.’C’ program to implement to searching using dynamic array:


   #include<stdio.h>
  #include<conio.h>
  #include<stdlib.h>
main(),
{
 float *arr, num;  /*array of real numbers */
 int size, i;
 clrscr();
 printf(“Enter the size of array :”);
 scanf(“%d”,&size);
 arr=(float*)malloc(size*sizeof(float));
 if(arr = = NULL)
 {
  printf(Memory allocation error!);
  exit(0);    /*to terminate program execution */
 }        /* end of it*/
 printf(“\nEnter  array elements:”);
 for(i=0;i<size;i++)
 scanf(“%f”,arr+i);                                      /*pointer addition */
 printf(“Enter the real number to search in array:”);
 scanf(“%f”,&num);
 for(i=0;i<size;i++)
   if(num==*(arr+i))
   break;                /*to terminate for loop */
 if(i==size)            /*if i=size then ‘break’ is not executed.
                               Element comparison is over */
 printf(“Search unsuccessful…”);
 else
 printf(“Search successful…”);
} /*end of main() */

3.’C’ program to count the frequency of a number in a dynamic array.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(),
{
  float *arr, num;  /*array of real numbers */
  int size, i, count=0;
  printf(“Enter the size of array :”);
  scanf(“%d”,&size);
  arr=(float*)malloc(size*sizeof(float));
  if(arr == NULL)
 {
   printf(Memory allocation error!);
   exit(0);    /*to terminate program execution */
 }        /* end of it*/
  printf(“\nEnter  array elements:”);
  for(i=0;i<size;i++)
  scanf(“%f”,arr+i);                                      /*pointer addition */
  printf(“Enter the number, the freq. of which is freq.:”);
  scanf(“%f”,&num);
   /*finding the frequency */
  for(i=0;i<size;i++)
   if(num==*(arr=i))
     count++;        /*count incremented by 1, whenever the num is equal to
                              the array element */                                
  printf(“\n Frequency of number %f is %d”,num,count);
} /*end of main() */

4.’C’ program to find the number of prime numbers stored in a dynamic array.

  #include<stdio.h>
 #include<conio.h>
 #include<stdlib.h>
 int prime(int num)
{
  int i;
  for(i=2;i<=num/2;i++)
  if(num%i == 0)               /*Non-prime */
     return 0;
  return 1;               /*prime */
 }
main()
{
  int  *arr, size, i, count=0;

  printf(“Enter the size of array :”);
  scanf(“%d”,&size);

  arr=(int*)malloc(size*sizeof(int));
  if(arr == NULL)
 {
   printf(“Memory allocation error!”);
   exit(0);                                /*to terminate program execution */
}                         /* end of it*/
 printf(“\nEnter  array elements:”);
 for(i=0;I<size;i++)
 scanf(“%d”,arr+i);                                      /*pointer addition */
 for(i=0;i<size;i++)
 if(prime(*(arr+i)) ==1)
 count++;                                    
 printf(“\nNumber of primes = %d”,count);
} /*end of main() *
© Copyright 2013 Computer Programming | All Right Reserved