Monday, December 28, 2009

Grid View Data Format String

DataFormatString property of GridView BoundField allows you to specify the format for number values and display them with different styles. You can display the number value as currency, number, decimal or hexadecimal formats.

List of Formats

1. {0:C} Currency format

2. {0:D} Decimal format

3. {0:E} Exponential format

4. {0:F} Fixed format

5. {0:G} General format

6. {0:N} Number format

7. {0:X} Hexadecimal format

8. {0:C2} Currency with 2 decimal places

9. {0:00.00} Number with 2 decimal places

10. {0:000} Number with 2 decimal places

You can also set the GridView Date Formats such as: {0:MM-dd-yyyy} to display the date with month number, day and year, {0:MMM dd, yyyy} to display the date with first three letters of month name, day and year. MMM dd, yyyy, MM-dd-yyyy, MM/dd/yyyy, dd/MM/yyyyy etc as per your requirement.

{0:MM-dd-yyyy HH:mm ss tt} - To display the time format along with date you can use HH for 24Hour, hh for hour, mm for minutes, ss for seconds and tt for AM/PM.

Monday, May 11, 2009

Insert data through Stored Procedure in ASP.net

Here we will insert firstname in table tbl_test through dbo.insertfirstname Stored Procedure. Below are the steps to implement it.

Step1 : Add this in web.config file
-----appSettings------
add key="cn" value="workstation id=SQL8;packet size=4096;user id=sa;password=amit;data source=USER1;initial catalog=amit; Connection Timeout=120;"
----appSettings------

Step2 : Add with other namespaces
using System.Data.SqlClient;

Step3: Add under partial class
SqlConnection con;
SqlCommand cmd;

Step4: create connection object in page load event
con = new SqlConnection(ConfigurationManager.AppSettings["cn"]);

Step5: execute insertion stored procedure in database query
create procedure dbo.insertfirstname(@firstname varchar(50)) as insert into tbl_test values(@firstname)

Step6: call this code at add button's Onclick event
cmd = new SqlCommand("dbo.insertfirstname", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@firstname", TextBox1.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();

Wednesday, May 6, 2009

Explain Connection Object

The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of Connection classes: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the information required to open a connection to the database.

The connection helps identify the data base server, the data base name, user name, password, and other parameters that are required for connecting to the data base.

Example:

SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=xyz;Integrated Security=SSPI");

Tuesday, May 5, 2009

ADO.Net Primary Objects

  1. Connection Object
  2. Command Object
  3. DataReader Object
  4. DataSet Object
  5. DataAdapter Object

Explain Command Object

It allows to manipulate database by executing stored procedure or sql statements.

A SqlCommand object allows us to specify what type of interaction we want to perform with a database.

For example, we can do select, insert, update, and delete commands on rows of data in a database table.

For Selecting data from datatable

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);

// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();

Example:

For Inserting data in datatable

// prepare command string

string insertString = @"insert into Categories(CategoryName, Description) values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";

// 1. Instantiate a new command with a query and connection

SqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send command

cmd.ExecuteNonQuery();


Explain DataReader Object

It provides a forward-only, read-only, connected recordset.

It is most efficient to use when data need not to be updated, and requires forward only traverse. In other words, it is the fastest method to read data.

Mostly Used:

  1. Filling dropdownlistbox.
  2. Comparing username and password in database

Example:

SqlDataReader rdr = cmd.ExecuteReader();

//Reading data

while (rdr.Read())
{

//Display data

string contact = (string)rdr["ContactName"];
string company = (string)rdr["CompanyName"];
string city = (string)rdr["City"];

}

Explain DataSet Object

Dataset is a disconnected, in-memory representation of data. It can contain multiple data table from different database.

They contain multiple Datatable objects, which contain columns and rows, just like normal data base tables. You can even define relations between tables to create parent-child relationships.

Example
DataSet dsEmp = new DataSet();

There are several ways of working with a DataSet, which can be applied independently or in combination. we can:

1. Programmatically create a DataTable, DataRelation, and Constraint within a DataSet and populate the tables with data.

2. Populate the DataSet with tables of data from an existing relational data source using a DataAdapter.

3. Load and persist the DataSet contents using XML.

For more understanding look for DataAdapter Object Article.

Explain DataAdapter Object

It populates dataset from data source. It contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database.

Example:
SqlDataAdapter daEmp = new SqlDataAdapter( "select EmpID, EmpName, Salary from Employees", conn);

Fill Method
It is used to populate dataset.
example: daEmp.Fill(dsEmp,"Employee");

Update Method
It is used to update database.
example: daEmp.Update(dsEmp,"Employee");

More about DataAdapter
DataAdapter object is like a bridge that links the database and a Connection object with the ADO.NET-managed DataSet object through its SELECT and action query Commands. It specifies what data to move into and out of the DataSet. Often, this takes the form of references to SQL statements or stored procedures that are invoked to read or write to a database.

Explain DataView

A DataView enables us to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. Using a DataView, we can expose the data in a table with different sort orders, and we can filter the data by row state or based on a filter expression.

It provides a means to filter and sort data within a data table.

Example:
DataView myDataView = new DataView(myDataSet.Tables["Customers"]);

// Sort the view based on the FirstName column
myDataView.Sort = "CustomerID";

// Filter the dataview to only show customers with the CustomerID of XYZ
myDataView.RowFilter = "CustomerID=XYZ";

Friday, May 1, 2009

Difference between ExecuteNonQuery, ExecuteScaler, ExecuteReader

Difference Angle

ExecuteNonQuery

ExecuteScaler

ExecuteReader

About

After Executing Sql statement Returns number of rows affected

Returns Single value, Executes first column first row only

Send the Command text to connection and builds a SqlDataReader.

When we use

ExecuteNonQuery is used to perform Catalog operation like Creating table in database or Changing of data in tables (without using Dataset) by using Insert, Update, Delete, create

Selecting only single fields like count field

When we manipulating with DataReader it used, Sending SQL Select statements to a database, Invoking Stored Procedures

Example

Example:
SqlCommand cmd = new SqlCommand("Insert Into SampleTable Values('1','2')",con);
//con is the connection object

con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed
This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.

Example : select count(*) from emp

ExecuteScalar is used to get aggregate value. ExecuteScalar will return only one value that is first column value of the first row in the executed query.

Example 2:
cmd.CommandText = "Select Name, DOB, from Emp where ID=1";
Dim strName As string = cmd.ExecuteScalar.ToString
This returns one value only, no recordsets.

Example:
SqlConnection con = new SqlConnection(constr);
//constructor can be connection of string.
SqlCommand cmd = new SqlCommand ("select * from emp", con);
con.Open();
SqlDataReader dr = cmd. ExecuteReader (CommandBehavior. CloseConnection);

while(dr.Read())
{
Console.WriteLine (dr.GetString(0));
}
dr.Close();

//Implicitly closes the connection because CommandBehavior. CloseConnection was specified.
ExecuteReader is used to get set records by specified query

Thursday, April 30, 2009

What is Boxing and Unboxing in .net?

Boxing:
It is a process of converting value type into Reference Type.

UnBoxing:
It is a reverse process of Boxing i.e. Converting Reference Type
into Value Type.

Here is the Example :

class Test
{
static void Main() {
int i = 123;
object o = i; //boxing
int j = (int) o; //unboxing
}
}

Wednesday, April 29, 2009

Diffrence between Data Reader, Dataset and Data Adapter

Difference  Angle

Data Reader

Dataset

Data Adapter

Disconnected mode

Connected mode

Disconnected mode

Disconnected mode

Forward Only

Yes

No

No

Read/Write

Read Only

Read/Write

Read/Write

Handling

Database Table

Can handle text file, XML file and Database table

Can handle text file, XML file and Database table

Storage Capacity

No storage

Temporary Storage Capacity

Temporary Storage Capacity

Accessibility

Can access one table at a time

Multiple table at a time

Multiple table at a time

Faster

Much faster than dataset

Less faster than data reader

Less faster than data reader

Useful Functions in ASP.net

1. Split Function in C#

Sample code:
string test = "afdas.;asdas.;asd";
string[] test1 = test.Split(';'); //For Character
string[] test2 = test.Split(new string[] { ".;" }, StringSplitOptions.None); //For String

Tuesday, April 28, 2009

Difference between ASP and ASP.net

Image Version (Click on image for enlarge version)





Text Version (See Below)

Difference Angle

ASP.Net

ASP

Generation

ASP.NET is the next generation of ASP to develop web Applications.(Latest)

After the introduction of ASP.NET, old ASP is called 'Classic ASP'.(old)

Language Support

ASP.NET supports more languages including C#, VB.NET, J# etc.

Classic ASP uses VB Script/JavaScript  for server side coding

Robustness and Reliability

ASP.net able to write much more robust and reliable programs

Not much robust and reliable

Server/HTML controls

ASP.NET offers a very rich set of controls called Server Controls and Html Controls. It is very easy to drag and drop any controls to a web form

In classic ASP, there was no server controls. You have to write all html tags manually

Code Execution

ASP.NET is compiled to efficient Microsoft Intermediate Language (MSIL) by CLR

ASP is interpreted

Database Interaction

ASP.NET uses the ADO.NET technology (which is the next generation of ADO).

Classic ASP uses a technology called ADO(ActiveX Data Objects) to connect and work with databases

File Extension

.ASPX

.ASP

OOPs

It is Object Oriented Programming, uses the event-driven model.

It is not truly Object Oriented; it uses more of a top-down programming style, where code execution begins at the top and executes down to the end

Framework Support

ASP.net Framework provides a very clean separation of code from content

ASP has Mixed HTML and coding logic

XML Support

Full XML Support for easy data exchange

No in-built support for XML.

 

 

 



Tuesday, March 31, 2009

Dyanamic item addition in drop down list by using C#

Below is the syntax for dyanamic item addition in drop down list by using C#

DropDownList1.Items.Add("Item1");
DropDownList1.Items.Add("Item2");
DropDownList1.Items.Add("Item3");

Find current day, month and year by using c#

Here is the syntax to find current day, month and year by using c#.net

String TodayDate = DateTime.Now.Date.Day.ToString();
String Todaymonth = DateTime.Now.Date.Month.ToString();
String Todayyear = DateTime.Now.Date.Year.ToString();

--------showing day, month and year in text boxes---------------
Date.Text = TodayDate;
month.Text = Todaymonth;
year.Text = Todayyear;

Here is the out put sample.
day=1
Month=4
year=2009

SQL Server Database Connection using C#.net and ASP.net

Step 1:
First of all add appSettings tag in web.config file under configuration tag

--------appSettings------------

add key="cn" value="workstation id=SQL8;packet size=4096;user id=user1;password=password1;data source=671.15.417.21;initial catalog=DBNews; Connection Timeout=120;"

--------appSettings------------


Step 2:
Add namespace given below.
using System.Data
using System.Data.SqlClient;


Step 3:
Add below code under partial class

SqlConnection con;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;

Step 4:
Call below code at Page Load event

con = new SqlConnection(ConfigurationManager.AppSettings["cn"]);
String sql = "select * from tbl_adminuser";
cmd = new SqlCommand(sql, con);
adp = new SqlDataAdapter(cmd);
ds = new DataSet();
adp.Fill(ds, "tbl_adminuser");

Step 5:
Show User password on the page.

TextBox1.Text=ds.Tables[0].Rows[0]["Password"].ToString();

Friday, March 20, 2009

ASP.net Basics

What is ASP.NET?
ASP.NET is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server.

ASP.NET is a Microsoft Technology
ASP stands for Active Server Pages
ASP.NET is a program that runs inside IIS
IIS (Internet Information Services) is Microsoft's Internet server
IIS comes as a free component with Windows servers
IIS is also a part of Windows 2000 and XP Professional

What is an ASP.NET File?
An ASP.NET file is just the same as an HTML file
An ASP.NET file can contain HTML, XML, and scripts
Scripts in an ASP.NET file are executed on the server
An ASP.NET file has the file extension ".aspx"

How Does ASP.NET Work?
When a browser requests an HTML file, the server returns the file
When a browser requests an ASP.NET file, IIS passes the request to the ASP.NET engine on the server
The ASP.NET engine reads the file, line by line, and executes the scripts in the file
Finally, the ASP.NET file is returned to the browser as plain HTML

What is ASP+?
ASP+ is the same as ASP.NET.

ASP+ is just an early name used by Microsoft when they developed ASP.NET.

ASP.NET is Not ASP
ASP.NET is the next generation ASP, but it's not an upgraded version of ASP.

ASP.NET is an entirely new technology for server-side scripting. It was written from the ground up and is not backward compatible with classic ASP.


ASP.NET is the major part of the Microsoft's .NET Framework.