CSHARP FOR BEGINNER

The things I learnt while I migrated from classic asp to asp.net is given here for my reference as well as for new beginners.

The Very First Video Tutorial for ASP.NET C#

If you are brand new to ASP.NET C#,

then have a look at this video tutorial.

It is simply superb.

 

Click here for the Video Tutorial

Your First Csharp Code

Learn ASP.NET(C#) By Examples

@ Nora Lamens 2009

Lesson-1

Save the following code as Ex01.aspx and run it in Browser.

<%@ Page Language="c#"%>
<html>
<head>
<title>Ex-01</title>
</head>
<body>
Welcome Raja
</body>
</html>

What you have learnt in this Lesson?

  • The word :Ex-01" is displayed on the Blue color TitleBar of Browser.
  • The word "Welcome Raja" is displayed in the body of the Browser.
  • This aspx file contains zero gram of c# code.
 

Lesson-2

Let us slightly modify the above code in our Lesson-2 and check the result:

<%@ Import Namespace="System" %>

<%@ Page Language="c#"%>
<html>
<head>
<title>Ex-01</title>
</head>
<body>
<%
string x = "Raja";
Response.Write("Welcome " + x);
%>

</body>
</html>

 

 

 

 

What you have learnt?

  • The Method Response.Write() is used to display values in the body.
  • "+" sign is used for concatenating text and variables. (VB uses "&" for concatenation)
  • Csharp code has been written between this tag : "<%.....................%>"
  • Each statement in Csharp ends with a Semicolon.
 

Lesson 3:

The code in Lesson-2 can be further complicated by introducing FUNCTIONS..

<%@ Import Namespace="System" %>
<%@ Page Language="c#"%>
<script runat="server">
public string myFunc(string x)
{
return "Welcome " + x;
}
</script>

<html>
<head>
<title>Ex-01</title>
</head>
<body>
<% Response.write(myFunc("Raja")) %>
</body>
</html>

 

 

Lesson 4:

In this lesson, we do nothing. We have simply replaced the Response.Write() by "=" short code.

<%@ Import Namespace="System" %>
<%@ Page Language="c#"%>
<script runat="server">
public string myFunc(string x)
{
return "Welcome " + x;
}
</script>
<html>
<head>
<title>Ex-01</title>
</head>
<body>
<%=myFunc("Raja") %>
</body>
</html>

 

Lesson 5:

Let us further complicate our code by creating METHODS inside CLASSES and keep these classes in a separate file called as CODE-BEHIND FILE.When we use code-behind, there will be TWO files. One is aspx file and another one is aspx.cs file

Code for Ex01.aspx file:

<%@ Page Language="C#" CodeFile="Ex01.aspx.cs" Inherits="Ex01" %>
<html>
<head>
<title>Ex-01</title>
</head>
<body>

</body>
</html>
Code for Ex01.aspx.cs file:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Ex01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
myMethod("Raja");
}

protected void myMethod(string x)
{
Response.Write("Welecome " + x);
}
}

The output of all the five lessons are same. you will get " Welcome Raja".

 

PHONE BOOK PROGRAM CODE IN ASP.NET CSHARP

A COMPLETE PROGRAM CODE IN ASP.NET CSHARP FOR PHONE BOOK APPLICATION

This code was tested ok. Simply copy these three files in a folder and run it and you will get the output as shown below.

 

Code for phonebook.xml
<?xml version="1.0" encoding="utf-8"?>
<guestbook>
<record>
<name>raja</name>
<email>raja@roja.com</email>
<mobile>99688888</mobile>
</record>
<record>
<name>roja</name>
<email>roaja@pooja.com</email>
<mobile>9968996877</mobile>
</record>
</guestbook>
Code for phonebook.aspx
<%@ Page Language="C#" AutoEventWireup="true" Debug="true" CodeFile="phonebook.aspx.cs" Inherits="phonebook" %>
<!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>Phone Book</title>
</head>
<body>
<form id="form1" runat="server">
<table border="1" bgcolor="#f0f0f0">
<tr>
<td style="width: 100px">
Name:</td>
<td style="width: 100px">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Email:</td>
<td style="width: 100px">
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Mobile:</td>
<td style="width: 100px">
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /></td>
</tr>
</table>

<br />
<asp:DataList ID="PhoneBook" Runat="server" Width="100%">
<ItemTemplate>

Name: <%# DataBinder.Eval(Container.DataItem, "name") %><br />
E-mail: <a href="mailto:<%# DataBinder.Eval(Container.DataItem, "email") %>"><%# DataBinder.Eval(Container.DataItem, "email") %></a><br />
Mobile: <%# DataBinder.Eval(Container.DataItem, "mobile") %>
<br />*****************************************<br />
</ItemTemplate>
</asp:DataList>
</form>
</body>
</html>


Code for phonebook.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

public partial class phonebook : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}

protected void Button1_Click(object sender, EventArgs e)
{
// Open the XML doc
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load(Server.MapPath("guestbook.xml"));
System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;

// Create new XML element and populate its attributes
System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
myXmlElement.SetAttribute("name", Server.HtmlEncode(txtName.Text));
myXmlElement.SetAttribute("email", Server.HtmlEncode(txtEmail.Text));
myXmlElement.SetAttribute("location", Server.HtmlEncode(txtMobile.Text));

// Insert data into the XML doc and save
myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
myXmlDocument.Save(Server.MapPath("guestbook.xml"));

// Re-bind data since the doc has been added to
BindData();
}

void BindData()
{
XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("phonebook.xml"));
DataSet myDataSet = new DataSet();
myDataSet.ReadXml(myXmlReader);
myXmlReader.Close();

PhoneBook.DataSource = myDataSet.Tables[0];
PhoneBook.DataBind();
}
}

SINGLE DIMENTIONAL ARRAY C#

ARRAY IN C#

OF ASP.NET

- SAMPLE PROGRAM CODE

Array is a frequently used concept in any Programming Language. Whichever language you are learning, you should know how create and manipulate an Array.

Here the complete code for webpage which uses a Single Dimentional Array is given. Just copy this code and save it as say : test.aspx and run it.

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

<script runat="server">

protected void Button1_Click(object sender, System.EventArgs e)
{
string[] myArray = { "raja","roja","pooja","kaja"};
Label1.Text = "My Friends are :<br />";
foreach (string myItem in myArray)
{
Label1.Text += myItem + "<br />";
}

}
</script>

<html >
<head id="Head1" runat="server">
<title>Array Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Button OnClick="Button1_Click" ID="Button1"
runat="server" Text="View My Friends"/>
</form>
</body>
</html>

Some useful Array Commands

string[] myArray = new string[5];

Label1.Text = MyArray.GetValue(2).ToString();

 

int [] myArray;
my Array = new int[5];

 

int [] myArray;
my Array = new int[3]{5, 12, 23};

 

string[] myArray = {"raja", "roja", "pooja"};

 

 

 

 

Important Properties of an Array:

GetLowerBound,GetUpperBound,IndexOf,GetValue,Length,



TWO DIMENTIONAL ARRAY C# CODE

C# code for

TWO DIMENTIONAL ARRAY

<%@ Page Language="C#" %>
<script runat="server">
void Page_Load()
{
if(Page.IsPostBack)
{
string [,] myArray = new string[3,2];
myArray[0,0] = "raja";
myArray[0,1] = "26";
myArray[1,0] = "roja";
myArray[1,1] = "21";
myArray[2,0] = "pooja";
myArray[2,1] = "18";
int recordID = Convert.ToInt32(TextBox1.Text);
Label1.Text = "Name :" + myArray[recordID,0];
Label1.Text = Label1.Text + ",Age : " + myArray[recordID,1];
}
}
</script>
<html>
<head>
<title>Array Example</title>
</head>
<body>
<form id="Form1" runat="server">
Enter the Record ID
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Get Name and Age" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Label


</form>
</body>
</html>



ASP.NET CODING FOR REPEATER CONTROL

ALL ABOUT

REPEATER CONTROL

ASP.NET VB code for Repeater Control

(program tested ok)

<%@ Page Language="vb" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load

Dim sql As String
Dim cmd As OleDbCommand
Dim rdr As OleDbDataReader
Dim connString As String
connString = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath("emp.mdb")
Dim conn As OleDbConnection = New OleDbConnection(connString)

conn.Open()
sql="SELECT * FROM emp"
cmd=New OledbCommand(sql,conn)
rdr=cmd.ExecuteReader()
repeater1.DataSource=rdr
repeater1.DataBind()
rdr.Close()
conn.Close()
end sub
</script>

<html>
<head></head>
<body>
<form id="Form1" runat="server">
<asp:Repeater id="repeater1" runat="server">
<HeaderTemplate>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#DataBinder.Eval(Container, "DataItem.empName")%></td>
<td><%#DataBinder.Eval(Container, "DataItem.age")%></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr bgcolor="#f0f0f0">
<td><%#DataBinder.Eval(Container, "DataItem.empName")%></td>
<td><%#DataBinder.Eval(Container, "DataItem.age")%></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>

C# code (with code-behind-file) for Repeater

(program tested ok)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="_Default" %>
<html>
<head></head>
<body>

<form id="Form1" runat="server">
<asp:Repeater id="repeater1" runat="server">

<HeaderTemplate>
<table>
<tr>
<th>Name</th>
<th>Age</th>

</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td><%#DataBinder.Eval(Container,"DataItem.EmpName")%></td>
<td><%#DataBinder.Eval(Container,"DataItem.Age")%></td>
</tr>
</ItemTemplate>

<AlternatingItemTemplate>
<tr bgcolor="#f0f0f0">
<td><%#DataBinder.Eval(Container,"DataItem.empName")%></td>
<td><%#DataBinder.Eval(Container,"DataItem.Age")%></td>
</tr>
</AlternatingItemTemplate>


<FooterTemplate>
</table>
</FooterTemplate>

</asp:Repeater>

<br />

Total Records:
<asp:Label ID=totalRecords runat=server></asp:Label>

</form>

</body>
</html>


 

CODE in the Code-behiind-file:Default.aspx.cs


using System;//this line must for Striang Variable
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;//this line is must
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String connString="Provider=Microsoft.Jet.OLEDB.4.0; data source =" + Server.MapPath("emp.mdb");
OleDbConnection conn=new OleDbConnection(connString);
conn.Open();
String sql="SELECT * FROM emp";
OleDbCommand cmd=new OleDbCommand(sql,conn);
OleDbDataReader rdr=cmd.ExecuteReader();
repeater1.DataSource=rdr;
repeater1.DataBind();
if (repeater1.Items.Count > 0)
{
totalRecords.Text = repeater1.Items.Count.ToString();
}
rdr.Close();
conn.Close();
}
}

 


Efficiency of Repeater Control:

  • Repeater control is simple and light weight for report generation.
  • Repeater control evaluates the data during runtime by late binding. So there will be a performance penalty.
  • Any kind of html markup codes can be addred to the repeater. That is why it is known as more flexible.
  • Datagrid is having in-buit Selection/Editing.But Repeater control does not have this facility.


Syntax of Repeater Control

Repeater control supports the following templates

HeaderTemplate
FooterTemplate
ItemTemplate
AlternatingItemTemplate
SeparatorTemplate( Styles for separating rows and columns)

The Syntax: of Repeater Control

<asp:Repeater id="idrepeater" runat="server" Datasource="<%# dataset %>" DataMember="table-inside-dataset">

  • <HeaderTemplate>..Header Format ..</HeaderTemplate>
  • <ItemTemplate> .. Item formats .. </ItemTemplate>
  • <FooterTemplate>..Header Format ..</FooterTemplate>

</asp:Repeater>

Meaning of DataBinder.Eval()

  • The System.Web.UI.DataBinder class provides a STATIC method DataBinder.Eval.
  • It evaluates the data at runtime by using late binding.

Repeater Example:

<asp:Repeater id="Repeater1" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>

<a href="<%#DataBinder.Eval(Container.DataItem("empID"))%>">
<%#DataBinder.Eval(Container.DataItem("empName"))%>

</a>

</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>

Repeater Example:

<asp:Repeater id="Repeater1" runat="server">
<HeaderTemplate>

</HeaderTemplate>


<ItemTemplate>
<a href="<%#DataBinder.Eval(Container.DataItem("empID"))%>">
<%#DataBinder.Eval(Container.DataItem("empName"))%>
</a> </ItemTemplate>

<AlternatingItemTemplate>

<font style="background-color:#f0f0f0"><a href = "<%#DataBinder.Eval(Container.DataItem("empID"))%>">
<%#DataBinder.Eval(Container.DataItem("empName"))%></a>

</font>

</AlternatingItemTemplate>

<SeparatorTemplate>
*******************************<br />
</SeparatorTemplate>


<FooterTemplate>

<p>Thank you</p>
</FooterTemplate>

</asp:Repeater>

Sample code for Binding a Repeater with SQLServer:


SqlConnection conn = new SqlConnection(connStr);


if (conn.State == ConnectionState.Closed)
{
conn.Open();
}


SqlCommand cmd = new SqlCommand("select * from emp", conn);

cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSetds = new DataSet();

da.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();


if (conn.State == ConnectionState.Open)
{
conn.Close();
}

ASP.NET-CSHARP-XML-AS-DATABASE

Working ASP.NET code

for using XML file as a Database

XML Code for emp.xml file
<?xml version="1.0" encoding="iso-8859-1"?>
<emp>
<record>
<name>Raja</name>
<age>25</age>
</record>
<record>
<name>Peter</name>
<age>23</age>
</record>
</emp>



ASP.NET Code for

simpleRepeater.aspx
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim empDataSet=New DataSet
empDataSet.ReadXml(MapPath("emp.xml"))
empRepeater.DataSource=empDataSet
empRepeater.DataBind()
end if
end sub
</script>
<html>
<body>

<form runat="server">
<asp:Repeater id="empRepeater" runat="server">

<HeaderTemplate>
<table border="1" >
<tr>
<th align="left">Name</th>
<th align="left">Age</th>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td><%#Container.DataItem("name")%> </td>
<td><%#Container.DataItem("age")%> </td>
</tr>
</ItemTemplate>

Just copy the above two files in proper location and open the file simpleRepeater.aspx. You will get the result like this :

Name Age
Raja 25
Peter 23

Here XML file acts just like a Database

LISTBOX LESSON 2 HOW TO MOVE DATA FROM LISTBOX TO ANOTHER

ListBox Lesson 2

Today we are going to learn how to Move the Data From One ListBox to Another?

 

Step 1: Drag and Drop Two ListBoxes,Three Buttons and One TextBox. Right Click on the ListBox1 and ListBox2 and set the property "SelectionMode=Multiple" as shown here:

Step 2: Properly modify the Code of aspx and aspx.cs files as shown here:

Code for ListBoxMove.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListBoxMove.aspx.cs" Inherits="ListBoxMove" %>
<!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>
<table >
<tr>
<td >
<asp:ListBox ID="ListBox1" runat="server"
SelectionMode="Multiple"
style="font-size:25px" Width="100px">
</asp:ListBox>
</td>
<td >
<asp:Button
ID="bnMoveRight"
runat="server"
Text="&gt;&gt;"
onclick="bnMoveRight_Click" />
<br />
<asp:Button
AccessKeyID="bnMoveLeft"
runat="server"
Text="&lt;&lt;"
onclick="bnMoveLeft_Click" />
</td>
<td>
<asp:ListBox
ID="ListBox2"
runat="server"
SelectionMode="Multiple"
style="font-size:25px" onselectedindexchanged="ListBox2_SelectedIndexChanged"
Width="100px">
</asp:ListBox>
</td>
</tr>
</table>

</div>
<asp:TextBox ID="TextBox1"
runat="server">
</asp:TextBox>
<asp:Button
ID="bnInsert"
runat="server"
onclick="bnInsert_Click"
Text="Insert into Box1" />
</form>
</body>
</html>

Code for ListBoxMove.aspx.cs

Note: When you double click on the Button, some of the codes such as "protected void........." will be automatically created. You have to type the inner content only.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ListBoxMove : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void bnMoveRight_Click(object sender, EventArgs e)
{
for (int i = ListBox1.Items.Count - 1; i >= 0; i--)
{
if (ListBox1.Items[i].Selected)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.RemoveAt(i);
}
}

}


protected void bnMoveLeft_Click(object sender, EventArgs e)
{
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.RemoveAt(i);
}
}
}
protected void bnInsert_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(TextBox1.Text);
TextBox1.Text = "";
}

protected void ListBox2_SelectedIndexChanged(object sender, EventArgs e)
{

}
}


Step 2: In the Solution Explorer, Right click on our aspx file and select "View in Browser" :

Step 3: You will get the output like this in Browser:

Step 4: Try to insert some data into Listbox1 as shown here:

Step 5: Click on the Move Button, to move the data from One ListBox to another.

ASP.NET Video Tutorial : How to Move Data from One ListBox to Another

ASP.NET-CSHARP-DROPDOWNLIST-EDIT FORM-SOURCE CODE

Code for creating a dropdownlist and displaying the selected record in a form:

What are we goining to Learn Today?

We are goining to Create a DropDownList. This List will contains names of employees. Once you select an employee and press the Edit button , the details of the employee will be displayed in a form.

 

Confusing? Dont worry. Have a look at this Screenshoot of output.

What is the advantage of this program? or Where can I use this program?

This can be used for Editing a particular record or for Deleting a Record.

 

Which language we are going to use? C# or VB ?

We will use C#

 

Are we going to create a single aspx file(with code inside) or there will be code-behind file also?

We first create a single file with code inside. Then We will create by the other method also.

What Database are we going to use?

We will use Oracle; and Table Name is Emp. This table has the fields:EmpID,EmpName

Just go through these code:

 

 

code for test.aspx (with c# code inside)

<%@ Page Language="C#" Debug="true" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.OracleClient" %>
<script runat="server">
void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
string sConn= "Data Source=SALES;user id=scott;password=tiger;";
string sql = "select * from emp";
OracleConnection myConn = new OracleConnection(sConn);
OracleCommand myCmd=new OracleCommand(sql,myConn);
DropDownList1.DataTextField="EmpName";
myConn.Open();
DropDownList1.DataSource = myCmd.ExecuteReader(CommandBehavior.CloseConnection);
DropDownList1.DataBind();
}
}
void editButton_click(Object sender, EventArgs e) {
string sConn = "Data Source=SALES;User Id=ctmslocal;password=ctms123;";
string selected_EmpName= DropDownList1.SelectedItem.Text;
string sql="select * from emp where EmpName='" + selected_EmpName+ "'";
OracleConnection myConn= new OracleConnection(sConn);
OracleCommand myCmd=new OracleCommand(sql,myConn);
myConn.Open();

OracleDataReader myReader = myCmd.ExecuteReader(CommandBehavior.SingleRow);
if (myReader.Read())
{
TextBoxEmpID.Text=myReader["EmpID"].ToString();
TextBoxEmpName.Text=myReader["EmpName"].ToString();
}

myReader.Close();
myConn.Close();
}
</script>
<html>
<head><title>Test</title></head>
<body>
<form id="Form1" runat="server">
Select the Employee to be edited:
<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>

<asp:Button id="editButton" onclick="editButton_click" runat="server" Text="Edit"></asp:Button>
<table border="1">
<tr>
<td>Employee Name</td>
<td>
<asp:TextBox id="TextBoxEmpID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> Emp Name </td>
<td>
<asp:TextBox id="TextBoxEmpName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
</html>

The Other method is code-behind method. Here there will be two files:

1.test.aspx

2.test.aspx.cs

Please compare the two methods and learn the difference.

Code for test.aspx
<%@ Page Language="C#" Debug="true" CodeFile="test.aspx.cs" Inherits="test" %>

<html>
<head><title>Test</title></head>
<body>
<form id="Form1" runat="server">
Select the Employee to be edited:
<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>

<asp:Button id="editButton" onclick="editButton_click" runat="server" Text="Edit"></asp:Button>
<table border="1">
<tr>
<td>Employee Name</td>
<td>
<asp:TextBox id="TextBoxEmpID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> Emp Name </td>
<td>
<asp:TextBox id="TextBoxEmpName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
</html>

Code for test.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OracleClient;

public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{
string sConn = "Data Source=SALES;user id=ctmslocal;password=ctms123;";
string sql = "select * from emp";
OracleConnection myConn = new OracleConnection(sConn);
OracleCommand myCmd = new OracleCommand(sql, myConn);
myConn.Open();
OracleDataReader myReader = myCmd.ExecuteReader(CommandBehavior.CloseConnection);
DropDownList1.DataTextField = "EmpName";


DropDownList1.DataSource = myCmd.ExecuteReader(CommandBehavior.CloseConnection);
DropDownList1.DataBind();
}
}

protected void editButton_click(Object sender, EventArgs e)
{
string sConn = "Data Source=SALES;User Id=ctmslocal;password=ctms123;";
string selected_EmpName = DropDownList1.SelectedItem.Text;
string sql="select * from emp where EmpName='" + selected_EmpName+ "'";
OracleConnection myConn= new OracleConnection(sConn);
OracleCommand myCmd=new OracleCommand(sql,myConn);
myConn.Open();
OracleDataReader myReader=null;
myReader=myCmd.ExecuteReader(CommandBehavior.SingleRow);
if (myReader.Read())
{
TextBoxEmpID.Text=myReader["EmpID"].ToString();
TextBoxEmpName.Text=myReader["EmpName"].ToString();
}

myReader.Close();
myConn.Close();
}

}

So you have seen the code.

Do you have any doubts?

Yes. What is the meaning of CommandBehavior.CloseConnection?

In this case you need not type the line "myConn.Close();" .The connection will be closed automatically by the reader.

What is the meaning of CommandBehavior.SingleRow?

Only one Row will be read.

 

 

To fillup the TextBox value, the following line is used here:

TextBox1.Text=myReader["EmpID"].ToString();

But, instead of TextBox, if there is a DropDownList, what code I should use?

Drop1.SelectedItem.Value=myReader["EmpID"].ToString();

What is the meaning of

"if (myReader.Read())" ?

It is equal to the classic asp code:

" If Not Rs.Eof "

Which means, "If there are records to read then proceed."

 

What is the meaning of the line:

" if (!Page.IsPostBack)" ?

This means :" If the page is opened for the very first time".

Actually when you type the url, the page is executed for the very first time. But, in the page, when you click the Edit button, the Request is sent to the Server and the Server is Returning the same page again. During this second time, the code inside the IF CONDITION will not be executed.

But you may have a doubt that if the IF CONDITION is not executed, then how the DropDownList will be populated in the next time? Actually It uses the concept called View State for this purpose.

 

What is View State?

Run the above aspx file from your browser. Then, in the browser, you select View > Source. Then Search for the word "VIEWSTATE".You will see the following line there:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMT Q1NzU4MDQwMA9kFgI CAQ9k FgICAQ8QDxYEHg1EYXRhVGV4dEZpZWxkBQhlbX Bfbm FtZR4LXyFEYXRhQm91bmRn ZBAV AgZyYW1 2gHUmFtZXNoZBUCBn JhbWVzaAdSYW1lc2hkFCsDAmdnZGRk PryumC8M/js87r1KlKqEC25BmVg=" />

Actually, the Complete Data in the DropDownList is encoded and kept there as a hidden text. When you press the Edit button, these data also goes to the Server. The very same data is returned back to you again. So there is no need of opening the database and retrieving the data again using that IF CONDITION.

Am I confusing. Then just leave this concept temporarily. You will learn later when you create a number of pages like this.

 

 

When I tried this code, I got an error against the line having OracleConnection like this :"Compiler Error Message: CS0246: The type or namespace name 'OracleConnection' could not be found (are you missing a using directive or an assembly reference?)"
". What is the problem?

Actually for the first time when you are using OracleConnection,etc, you should make a Reference. For this you can follow this Procedure: Website Menu >Add Reference > .Net Tab > Select System.Data.OracleClient > Click OK.

What is AuotEventWireup and how to use it

What is AUTOEVENTWIREUP?

When to use AutoEventWireup="True"?

Just imagine there is a button with name "Button1" in a web page.

If the user clicked that button, a message "hello" should be displayed.

How you will write code for this job?

<asp:button id="Button1" OnClick="Button1_Click" />

Here the Button1's Click EVENT is WIRED to Button1_Click Method.

If you remove the words OnClick="Button1_Click" in the above code,

then the method will NOT be called. Because there is no wiring (no binding) between the Event and the Method.

But AutoEventWireup=true means, the program should

automatically understand that the method "Button1_Click" is intended for the Click Event of Button1 and

it should AUTOMATCALLY call this method.

The above example is just to explain the meaning f EVENT and WIREUP.

In actual sense, even if AutoEventWireup=True,even then OnClick="SomeMethodName" is a must.

Because the AutoEventWireup is applicable only to Page Events such as Page_Load,Page_Unload,Page_Init.

And AutoEventWireup is Not Applicable to other things such as Button,etc.

 

Put together, if you use AutoEventWireup="False" then, you have to SPECIFICALLY call the

Page_Load to use this method. The example of how to call the Page_Load method is given Below:

public partial class _Default : Page
{
public _Default()
{
Load += new EventHandler(Page_Load);
}

protected void Page_Load(object sender, EventArgs e)
{
dododododo
}
}

 

 

 

How to Create HyperLink in a Data Grid

How to create Hyper Link in a DataGrid?

Step : 1

First Create the Basic and Simple GridView. The code will look like this :

<asp:gridview ID="Gridview1" runat="server" AutoGenerateColumns="False"
DataKeyNames="EMP_ID" DataSourceID="myconn">
<Columns>
<asp:BoundField DataField="EMP_NAME" HeaderText="EMP_NAME"
SortExpression="EMP_NAME" />
<asp:BoundField DataField="SALARY" HeaderText="SALARY"
SortExpression="SALARY" />
<asp:BoundField DataField="EMP_ID" HeaderText="EMP_ID" ReadOnly="True"
SortExpression="EMP_ID" />
</Columns>
</asp:gridview>

The output for the above code will look like this:

EMP_NAME SALARY EMP_ID
ROJA 2000 6
RAJA   5

 

Step-2

Now Let us modify one of the columns as shown in red here:

<asp:gridview ID="Gridview1" runat="server" AutoGenerateColumns="False"
DataKeyNames="EMP_ID" DataSourceID="myconn">
<Columns>
<asp:BoundField DataField="EMP_NAME" HeaderText="EMP_NAME"
SortExpression="EMP_NAME" />
<asp:BoundField DataField="SALARY" HeaderText="SALARY"
SortExpression="SALARY" />
<asp:TemplateColumn HeaderText="Edit">
<ItemTemplate>
<asp:HyperLink Runat="server" NavigateUrl='<%# _
"EmpEdit.aspx?Emp_ID=" & Container.DataItem("Emp_Id") +& "&Emp_Name=" & Container.DataItem("Emp_Name") %>' />
</ItemTemplate>
</asp:TemplateColumn>

</Columns>
</asp:gridview>

 

 

Login Form - Code in ASP.NET Csharp

Today what we are going to Learn?

LET US CREATE A SIMPLE LOGIN FORM TODAY

 

What Language are we going to use?

Let us use C# with code-behind.

How many files will be there in this program?

The program contains two files: login.aspx and login.aspx.cs. In the Login.aspx the form will be there and the csharp code will be in login.aspx.cs.

What about Database?

We will create myDatabase.mdb in MS Access. Inside this mdb we will create a table with name "LOGIN". And insert the data as shown here:

How the output of our Login Form will look Like?

Have a look at this Screenshot:

 

 

Can you first show me the code? Code for Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" Debug="true" CodeFile="login.aspx.cs" Inherits="login" %>

<!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>Login</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" ></asp:Label>
<br />
User Name: <asp:TextBox ID="UserId" runat="server" /><br />
Password: <asp:TextBox ID="Pwd" runat="server" /><br />
<asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" />
</div>
</form>
</body>
</html>

Code for Login.aspx.cs
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;
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login_Click(object sender, EventArgs e)
{
string sConn = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("myDatabase.mdb");
string sCmd = "Select Count(*) From login Where UserId = ? and Pwd= ?";
int cnt = 0;
OleDbConnection myConn = new OleDbConnection(sConn);
OleDbCommand myCmd = new OleDbCommand(sCmd, myConn);
myCmd.Parameters.AddWithValue("", UserId.Text);
myCmd.Parameters.AddWithValue("", Pwd.Text);
myConn.Open();
cnt = (int)myCmd.ExecuteScalar();
if (cnt == 0) { Label1.Text = "Invalid UserId or Password"; }
else { Response.Redirect("Welcome.aspx"); }
}
}

I have installed Visual Web Developer 2008. But I dont know how to start to create this page. Can you explain, in a step-by-step way?

Step 1: Open the Web Developer. The screen will look like this:

Click on the Create Web Site to create a NEW website. You will get the screen like this:

Have A look at screenshot. I have selected website=ASP.NET, Language=C# and selected a folder.The folder name was by default showing it as "website" but I have changed it into "TUTORIAL". and when I pressed OK, I got the screen like this:

 

Now, by default, Default.aspx has been created. But I dont want this file. I could have renamed this file into Login.aspx. But I am not going to rename it. Let us create a new file with name Login.aspx. The Steps are:

Step1: In the solution explorer, right click on the Tutorial web site. You will get a context Menu. From the Content Menu, Select "ADD NEW ITEM". See the shot:

Step 2: In the Add New Item, I have selected WEBFORM,I have typed my file name as Login.aspx, I have selcted C# as my language and I have selected "PLACE CODE IN SEPARATE FILE" which means, code-behind-method.

Then, From the Toolbox, I dragged and dropped 1 Label,2 TextBox and 1 Button into the <div> tag.

 

Save this file and right click on the "login.aspx" in the Solution Explorer and select "VIEW IN BROWSER". You should get the output like this:

Next, copy the code of login.aspx.cs I have given above and paste it into YOUR login.aspx.cs.

But how to create login.aspx.cs file?

When you create login.aspx, this login.aspx.cs is also created automatically. Are you able to see a plus sign on the left side of login.aspx in solution explorer. Click on this plus sign and you will see the cs file. Note: cs stands for csharp.

I am not able to see the SOLUTION EXPLORER OR TOOL BOX.Why?

 

If the SOLUTION EXLORER or TOOLBOX is not visible, then open the view View Menu and see there.

 

What is ADO.NET | Data Provider | DataSet

What is the meaning of this line in ASP.NET :

<%@ import Namespace="System.Data.OracleClient" %>

or

<%@ import Namespace="System.Data.SqlClient" %>

or

<%@ import Namespace="System.Data.Oledb" %>

or

<%@ import Namespace="System.Data.Odbc" %>

 

If you are using any one of the above lines in your code ,that means you are using ADO.NET to access data. And inside the code you will be using the corresponding DATAPROVIDER listed here.

Data Provider for Oracle (System.Data.OracleClient).

Data Provider for SQL Server (System.Data.SqlClient).


Data Provider for OLEDB (System.Data.OleDb).


Data Provider for ODBC (System.Data.Odbc).

ADO.NET is nothing but a set of classes which are used for accessing the database.

(ADO stands for Microsoft Activex Data Object)

 

Actually this DataProvider is again divided into a number of objects like this:

Connection object ( OracleConnection,SqlConnection, OleDbConnection, OdbcConnection)


Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand)


DataReader object (SqlDataReader, OleDbDataReader, OdbcDataReader, OracleDataReader)


DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter).

Apart from the above, the ADO.NET consisits of another item known as DATATSET.


 

 

Carefully watch the Diagram given at the top. To get data from the database, you have to follow the Red Path or the Blue Path. In the Red Path, DataReader is there. It is very fast. But it is forward-only which means it is useful for JUST display the records (not good for updating).

The Blue path has DataSet which has lot many features.


 

CSHARP command parameter concepts

<%@ Page Language="C#" Debug="true"%>
<%@ Import Namespace="System.Data.OleDb" %>
<%
string sConn;
sConn= @"Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:/emp.mdb";
string sql=@"select [name] from emp where EmpID=@EmpID";
string empName;
int sEmpId=25;
OleDbConnection conn=new OleDbConnection(sConn);
OleDbCommand cmd=new OleDbCommand(sql,conn);
cmd.Parameters.Add("@EmpID",OleDbType.Integer);
cmd.Parameters["@EmpID"].Value=sEmpId;
conn.Open();
empName=cmd.ExecuteScalar().ToString();
conn.Close();
Response.Write(empName);
%>

Why @ symbol is used in string

 

Why "@" symbol is used in Strings?

The Wrong way of writng a string:

string x="c:\abc\hello.txt";

The Right way of writing the above string:

string x=@"c:\abc\hello.txt";

What is the difference between these two?

When you are using "@" symbol, you mean that the text is just a literal. But if you dont use "@" symbol, in the above case, the BACKSLASH will be treated as ESCAPE SEQUENCEand it will create errrors.

 

Thanks for Your Visit

Google Search
Disclaimer and Copy Right