Saturday, December 14, 2013

How to dynamically use SQLDataSource with GridView in ASP.Net and C#

SQLDataSource is a great tool which can be used with the famous GridView control to view and edit data with at ease. This tutorial is for those developers who wants to use these two powerful controls to build dynamic web application in a simple way.


TestPage2.aspx File

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage2.aspx.cs" EnableViewState="true" Inherits="Test.WebForm2" %>

<!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:Image ID="img" runat="server" ImageUrl="~/App_Data/restrict/indianvivah.jpg" />
        <asp:Image ID="Image1" runat="server" />

        <asp:GridView ID="gridView" runat="server"
            DataSourceID="sqlDataSource" DataKeyNames="testId"
            AutoGenerateEditButton="true"
            AutoGenerateDeleteButton="true">

        </asp:GridView>

        <asp:SqlDataSource ID="sqlDataSource" runat="server" />
    </div>
    </form>
</body>

</html>



TestPage2.aspx.cs  File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.Configuration;

namespace Test
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int testid=0;

            if (Request.QueryString["testid"] != null)
            {
                testid=Convert.ToInt16(Request.QueryString["testid"]);
            }

            PopulateGridView(testid);
        }

        public void PopulateGridView(int testid)
        {
            //Getting the connection string from web.config file
sqlDataSource.ConnectionString = WebConfigurationManager.ConnectionStrings["conStr"].ToString();

//Selecting dynamic query for the sqlDataSource and later the extracted   //resultset will be displayed on the GridView. Interesting fact is we don't //need to use GridView.DataBind() method.
            //SQLDataSource control will take care that internally.
            if (testid == 0)
            {
                sqlDataSource.SelectCommand = "Select * from test";
            }
            else
            {
sqlDataSource.SelectCommand = "Select * from test where testid=" + testid;
            }

//Update statement. Here the Primary key of the table is testId and that has //been mentioned as
            //DataKeyNames="testId" in the GridView control on .aspx page.
sqlDataSource.UpdateCommand = "Update test set name=@name, address=@address where testId=@testId";

            //Delete statement.
            sqlDataSource.DeleteCommand = "Delete test where testId=@testId";

        }
    }

}


Tuesday, May 21, 2013

How to implement spinner onItemSelected in Android


This discussion can be useful for following types of question as well
  • How an event can be fired by selecting a combo box / Drop Down List box in android? 
  • How spinner's activity can be tracked on a change of a item selection?
Assume a scenario where a spinner will hold the Name of some students and upon selecting a Name the corresponding age will be populated in a EditText. To develop this task you have to work on the following points.
  1. Implement the interface OnItemSelectedListner on the Activity class in which you have your spinner.
  2. Add two contracted method onItemSelected and onNothingSelected inside your Activity class.
  3. Do something so the Spinner gets populated when the page is created.
  4. Put some code so that the EditText get filled when the Spinner's selection has been changed.
package com.example.testproject;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

/**
 * This is the class for this activity and it implements 
 * the Interface OnItemSelectedListener
 * @author Avijit
 *
 */
public class MainActivityActivity extends Activity 
     implements OnItemSelectedListener {
 Spinner spName;
 EditText txtAge;

  List<String> listName=new ArrayList<String>();
 List<String> listAge=new ArrayList<String>();

  /**
  * onCreate method is fired for initializing
  * your activity
  */
 protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main_activity);

   spName=(Spinner)findViewById(R.id.spinnerName);
  txtAge=(EditText)findViewById(R.id.editTextAge);

   //This method populate the ArrayList<String> and then 
  //use that ArrayList to ArrayAdapter which eventually 
  //is the source of the Spinner data
  populateSpinner();
  
  //Here Spinner has been set this Class for Listen on any
  //changes by selecting any of its item which eventually 
  //trigger the method onItemSelected.
  spName.setOnItemSelectedListener(this);

  }

  public void populateSpinner(){
  listName.add("Arnold");
  listName.add("Peter");
  listName.add("John");

   ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,listName);
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spName.setAdapter(adapter);

   listAge.add("14");
  listAge.add("15");
  listAge.add("16");
 }

  /**
  * This method is fired when something selected on the Spinner.
  */
 public void onItemSelected(AdapterView<?> parentView,View v,int position,long id){
  String strAge=listAge.get(position).toString();
  txtAge.setText(strAge);
 }

  public void onNothingSelected(AdapterView<?> parentView){
  //
 }

}


The main_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivityActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Spinner
        android:id="@+id/spinnerName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="36dp" />

    <EditText
        android:id="@+id/editTextAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/spinner1"
        android:layout_marginTop="24dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout>







Saturday, May 18, 2013

Boxing and UnBoxing in C#


Boxing means to create an object by boxed a type inside it. In a simpler way boxing is a process by which a value type is converted to  an object type.

Example:-

int a=10;
object obj=a;

When this object is transformed to its real type by casting the object then it is called as Unboxing.

Example:-

obj=10;
a=(int)obj;

What is type casting in Java



Automatic Type Conversion happens when two types are compatible with each other  (example int and short)  and the destination type is larger than the source type.


public class TypeCasting {
public static void main(String[] args) {

short s=5;
int i=6;
 
  i=s;
  //This is ok since int type is larger than short
  //to hold the value of short and for that nothing
  //extra is required

System.out.println("int value is " + i);
}
}


Ouput:-
int value is 5


Now consider the second scenario where we are trying to assign an int value to a short variable.


i=12;
s=i; 
//This will be a compile error since short is smaller than int
//and for that short cannot get the value of int by 
//Automatic Type Conversion. Here an explicit casting is required
//by which the int will be converted as short.

So the whole code will be


public class TypeCasting {
public static void main(String[] args) {

short s=5;
int i=6;
i=s;
System.out.println("int value is " + i);

i=12;

s=(short)i; 
  //This is type casting where int type is converted to
  //short type.

System.out.println("short value is " + s);
}
}


Ouput:-

int value is 5
short value is 12





















AutoBoxing and UnBoxing in Java with Example


After Java 1.5 is introduced the concept of AutoBoxing and UnBoxing (Auto-UnBoxing) comes into picture. In Java when the primitive types like int, double etc. are converted into their object class type (wrapper class type) like Integer, Double then it is called as AutoBoxing.

Example:-

Integer i=10; //Here AutoBoxing is happening from Primitive to Wrapper

When this wrapper object is transformed into its primitive type then it is called as UnBoxing.

Example:-

int iInt=i; //Here Unboxing is happening from Wrapper to Primitive
System.out.println("The value of int is " + iInt);