Search This Blog

2010/01/17

Trapping Enter Key pressed on TextBox with VB.NET:

Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
Friend WithEvents TextBox3 As System.Windows.Forms.TextBox
Private Sub InitializeComponent()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.TextBox2 = New System.Windows.Forms.TextBox()
Me.TextBox3 = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(64, 32)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.TabIndex = 0
Me.TextBox1.Text = ""
'
'TextBox2
'
Me.TextBox2.Location = New System.Drawing.Point(64, 64)
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.TabIndex = 1
Me.TextBox2.Text = ""
'
'TextBox3
'
Me.TextBox3.Location = New System.Drawing.Point(64, 96)
Me.TextBox3.Name = "TextBox3"
Me.TextBox3.TabIndex = 2
Me.TextBox3.Text = ""
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.TextBox3, Me.TextBox2, Me.TextBox1})
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)

End Sub

#End Region



Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) = 13 Then
SendKeys.Send("{TAB}")
End If
End Sub

Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
End Sub

Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Asc(e.KeyChar) = 13 Then
SendKeys.Send("{TAB}")
End If

End Sub
End Class

The 8 -Digited Numeric TextBox with VB.NET:

Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Private Sub InitializeComponent()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(80, 72)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.TabIndex = 0
Me.TextBox1.Text = ""
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(48, 40)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(164, 15)
Me.Label1.TabIndex = 1
Me.Label1.Text = "8 digited numeric Textbox"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label1, Me.TextBox1})
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)

End Sub

#End Region

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim str As String = TextBox1.Text

If e.KeyChar.IsLetter(e.KeyChar) Then
e.Handled = True
End If

If e.KeyChar.IsPunctuation(e.KeyChar) Then
e.Handled = True
End If
If e.KeyChar.IsSymbol(e.KeyChar) Then
e.Handled = True
End If

If Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Then
If str.Length = 8 Then
e.Handled = True
MessageBox.Show("Atmost 8 Digited Number are allowed")
End If
End If

End Sub
End Class

List Based Collection

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace OOPLib
{
class Library
{

}

class Person
{
public string PersonName;
public string PersonAddress;
public string PersonEmailAddress;
public Boolean PersonIsMale;
public DateTime PersonBirthDate;

//contructor of person class
public Person(string Name, string Adr, string Email, Boolean IsMale, DateTime BirthDate)
{
this.PersonName = Name;
this.PersonAddress = Adr;
this.PersonBirthDate = BirthDate;
this.PersonEmailAddress = Email;
this.PersonIsMale = IsMale;
}
public Person()
{
}
}//

//Author Class is derived from Person
class Author:Person
{
Weblinks AuthorWebs;

//constructor for author class
Author(Person p,Weblinks links)
{
this.PersonEmailAddress = p.PersonEmailAddress;
this.AuthorWebs = links;

this.PersonName = p.PersonName;
this.PersonAddress = p.PersonAddress;
this.PersonBirthDate = p.PersonBirthDate;
this.PersonIsMale = p.PersonIsMale;
}
}//

//List based collection of author objects
class Authors : CollectionBase
{
public void Add(Author newAuthor)
{
List.Add(newAuthor);
}
public void Remove(Author newAuthor)
{
List.Remove(newAuthor);
}
public Author this[int AuthorIndex]
{
get
{
return (Author)List[AuthorIndex];
}
set
{
List[AuthorIndex] = value;
}
}
}//

public class PrintedMedia
{
public string Id;
public string Name;
public long Price;
public string Publisher;

//constructor of PrintMedia Class
public PrintedMedia (string id,string name,long price ,string publisher)
{
this.Id = id;
this.Name = name;
this.Price = price;
this.Publisher = publisher;
}
//Default constructor
public PrintedMedia()
{
}
}//

//Book Class derived from PrintedMedia
class Book:PrintedMedia
{
string BookISBN;
Authors BookAuthors;
int BookCopies;
string BookEdition;
string BookCatagory;
Weblinks BookWebRef;

//constructor of book class
public Book(string ISBN, Authors newAuthors, int Copies, string Edition, string Catagory,Weblinks webref)
{
this.BookAuthors = newAuthors;
this.BookCatagory = Catagory;
this.BookCopies = Copies;
this.BookEdition = Edition;
this.BookISBN = ISBN;
this.BookWebRef = webref;
}
public Book()
{
}
}//

public enum PeriodicalTypes
{
Weekly,BiWeekly,Monthly,BiMonthly,SixMonthly,Yearly
}

//Periodical class inherit from PrintedMedia Class
class Periodical : PrintedMedia
{
PeriodicalTypes PeriodicalType;
DateTime PeriodicalIssueDate;


Periodical(PrintedMedia p,PeriodicalTypes q,DateTime IssueDate)
{
this.Id = p.Id;
this.Name = p.Name;
this.Price = p.Price;
this.Publisher = p.Publisher;
this.PeriodicalType = q;
this.PeriodicalIssueDate = IssueDate;
}
}//


//List Based Collection class for Periodicals
class Periodicals : CollectionBase
{
public void Add(Periodical newPeriodical)
{
List.Add(newPeriodical);
}
public void Remove(Periodical newPeriodical)
{
List.Remove(newPeriodical);
}
public Periodical this[int PeriodicalIndex]
{
get
{
return (Periodical)List[PeriodicalIndex];
}
set
{
List[PeriodicalIndex] = value;
}
}
}
//List Based Collection Class for Book's Web References
class Weblinks:CollectionBase
{
public void Add(string newUrl)
{
List.Add(newUrl);
}

public void Remove(string newUrl)
{
List.Remove(newUrl);
}
public string this[int WebIndex]
{
get
{
return (string)List[WebIndex];
}
set
{
List[WebIndex]=value;
}
}
}//


//List Based Book object collection
class Books : CollectionBase
{
public void Add(Book newBook)
{
List.Add(newBook);
}

public void Remove(Book newBook)
{
List.Remove(newBook);
}

public Book this[int BookIndex]
{
get
{
return (Book)List[BookIndex];
}
set
{
List[BookIndex] = value;
}
}
}//

//Member class derived from person class
class Member : Person
{
string MemberID;
long MemberDeposite;
Books BorrowedBooks;
Periodicals BorrowedPeriodicals;

Member(string ID, long Deposite, Person p,Books Borrowed,Periodicals Periodicals)
{
this.MemberID = ID;
this.MemberDeposite = Deposite;

this.PersonName = p.PersonName;
this.PersonAddress = p.PersonAddress;
this.PersonBirthDate = p.PersonBirthDate;
this.PersonEmailAddress = p.PersonEmailAddress;
this.PersonIsMale = p.PersonIsMale;
this.BorrowedBooks = Borrowed;
this.BorrowedPeriodicals = Periodicals;
}

}//

//List Based Collection of Member Objects

class Members : CollectionBase
{
public void Add(Member newMember)
{
List.Add(newMember);
}
public void Remove(Member newMember)
{
List.Remove(newMember);
}
public Member this[int MemberIndex]
{
get
{
return (Member)List[MemberIndex];
}
set
{
List[MemberIndex] = value;
}
}
public enum StaffPositions
{
Librarian, DeputyLibrarian, Clerk, Peon
}

public class StaffMember : Person
{
StaffPositions staffType;

StaffMember(Person p, StaffPositions q)
{
this.PersonAddress = p.PersonAddress;
this.PersonBirthDate = p.PersonBirthDate;
this.PersonEmailAddress = p.PersonEmailAddress;
this.PersonIsMale = p.PersonIsMale;
this.PersonName = p.PersonName;
staffType = q;
}

}//


//List Based collection of StaffMember objects
class StaffMembers : CollectionBase
{
public void Add(StaffMember newMember)
{
List.Add(newMember);
}
public void Remove(StaffMember newMember)
{
List.Remove(newMember);
}
public StaffMember this[int MemberIndex]
{
get
{
return (StaffMember)List[MemberIndex];
}
set
{
List[MemberIndex] = value;
}
}

}
}
}

Downloading data as Excel Sheet:

C# Code Snipet:

GridView GridViewDump = new GridView(); GridViewDump.HeaderStyle.Font.Bold = true;

/*
Using Normal database connectivity code
Create dataset ds fill it using dataadapter
*/

GridViewDump.DataSource =ds;
GridViewDump.DataBind();

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Report.xls");

Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);


GridViewDump.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

Displaying records from Mysql server in gridview:



C# Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySql.Data;
using MySql.Data.MySqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection mcon = new MySqlConnection("datasource=localhost;username=root;password=admin;database=sangram");
mcon.Open();
MySqlDataAdapter mda = new MySqlDataAdapter("select * from course", mcon);
DataSet ds = new DataSet();
mda.Fill(ds, "course");
GridView1.DataSource = ds;
GridView1.DataBind();

}
}

Html:

%@ 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">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>

constructor overloading

Class having two contructor in C#:

using System;
using System.Collections.Generic;
using System.Text;

namespace ClassWithConstructor
{
class Program
{
static void Main(string[] args)
{
DrinkBottle db = new DrinkBottle("Pepsi", 250,"Caffetino");
db.openBottle();
Console.ReadKey();
}
}

public class DrinkBottle
{
string Brand;
int Size;
string Flavour;
string MonthOfManiFacture;

public DrinkBottle(string brand, int size, string flavour)
{
Brand=brand;
Size=size;
Flavour = flavour;
MonthOfManiFacture = DateTime.Today.ToString() ;
}
public DrinkBottle(string brand, int size, string flavour,string MFM)
{
Brand = brand;
Size = size;
Flavour = flavour;
MonthOfManiFacture = MFM;
}
public void openBottle()
{
Console.WriteLine("Specification of Bottle Opened");
Console.WriteLine("Brand:"+Brand );
Console.WriteLine("Size"+Size);
Console.WriteLine("Flavour"+Flavour);
Console.WriteLine("Manifacturing Date"+MonthOfManiFacture); }
}
}

COM & .NET

ACTIVE X DLL PROJECT MeanCaslculator2 having Class MeanCalc2:

Notes:1)Build DLL, Register it.

Option Explicit
Dim mintValue As Integer
Dim mdblValues() As Double
Dim mdblMean As Double

Public Sub Class_Initialize()
Reset
End Sub

Public Sub AddInput(InputValue As Double)
mintValue = mintValue + 1
ReDim Preserve mdblValues(mintValue)
mdblValues(mintValue) = InputValue
End Sub

Public Sub DoCalculation()
Dim iValue As Integer
mdblMean = 0#
If (mintValue = 0) Then Exit Sub

For iValue = 1 To mintValue
mdblMean = mdblMean + mdblValues(iValue)
Next iValue

mdblMean = mdblMean / mintValue

End Sub

Public Function GetOutput() As Double
GetOutput = mdblMean
End Function

Public Sub Reset()
mintValue = 0
End Sub


********************************

Using ACTIVEX DLL CREATED FROM VB 6.0 in VB.NET (Early Binding):

Notes:
1)Add reference to ActiveX DLL MeanCalc2 having Class MeanCalc2

Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
Friend WithEvents CmdADD As System.Windows.Forms.Button
Friend WithEvents CmdReset As System.Windows.Forms.Button
Friend WithEvents CmdCalculate As System.Windows.Forms.Button
Private Sub InitializeComponent()
Me.CmdADD = New System.Windows.Forms.Button()
Me.CmdReset = New System.Windows.Forms.Button()
Me.CmdCalculate = New System.Windows.Forms.Button()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.TextBox2 = New System.Windows.Forms.TextBox()
Me.SuspendLayout()
'
'CmdADD
'
Me.CmdADD.Location = New System.Drawing.Point(216, 24)
Me.CmdADD.Name = "CmdADD"
Me.CmdADD.TabIndex = 0
Me.CmdADD.Text = "ADD"
'
'CmdReset
'
Me.CmdReset.Location = New System.Drawing.Point(72, 56)
Me.CmdReset.Name = "CmdReset"
Me.CmdReset.TabIndex = 1
Me.CmdReset.Text = "RESET"
'
'CmdCalculate
'
Me.CmdCalculate.Location = New System.Drawing.Point(216, 88)
Me.CmdCalculate.Name = "CmdCalculate"
Me.CmdCalculate.Size = New System.Drawing.Size(80, 23)
Me.CmdCalculate.TabIndex = 2
Me.CmdCalculate.Text = "CALCULATE"
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(32, 24)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New System.Drawing.Size(168, 20)
Me.TextBox1.TabIndex = 3
Me.TextBox1.Text = ""
'
'TextBox2
'
Me.TextBox2.Location = New System.Drawing.Point(32, 88)
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New System.Drawing.Size(168, 20)
Me.TextBox2.TabIndex = 4
Me.TextBox2.Text = ""
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(376, 266)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.TextBox2, Me.TextBox1, Me.CmdCalculate, Me.CmdReset, Me.CmdADD})
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)

End Sub

#End Region
Dim myObj As New MeanCalculatorNet.MeanCalc2()

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub CmdADD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdADD.Click
myObj.AddInput(Val(TextBox1.Text))
End Sub

Private Sub CmdReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdReset.Click
myObj.Reset()
End Sub

Private Sub CmdCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdCalculate.Click
myObj.DoCalculation()
TextBox2.Text = myObj.GetOutput()
End Sub
End Class
1)Create a vb 6.0 standard exe project add a textbox,a lavel ,add,calculate,reset
command button
2)copy assembly of NewMegacalc2 and NewMeanCalculator in current directory
3) copy type libraries for both of these.

Dim mobjCalc As NewMeanCalculator.MeanCalc
Dim mobjmega As NewMegaCalc2.IMegaCalc

Private Sub CmdAdd_Click()
mobjmega.Addinput (Text1.Text)
End Sub

Private Sub CmdCalculate_Click()
mobjmega.doCalculation
Text1.Text = mobjmega.GetOutput()
End Sub

Private Sub CmdReset_Click()
mobjmega.Reset
End Sub

Private Sub Form_Load()
mobjCalc = New NewMeanCalculator.MeanCalc
mobjmega = mobjCalc
End Sub

********************
Importing Vb.net assembly in vb 6.0:
Pre-requisite:

1)Create Class Library in VB.net add reference to NewMegaCalc2 a .Net Assembly
2)Add Following code

Public Class MeanCalc
Implements NewMegaCalc2.IMegaCalc

Dim mintValue As Integer
Dim mdblValues() As Double
Dim mdblMean As Double

Public Sub AddInput(ByVal InputValue As Double) Implements NewMegaCalc2.IMegaCalc.Addinput
mintValue = mintValue + 1
ReDim Preserve mdblValues(mintValue)
mdblValues(mintValue - 1) = InputValue
End Sub
Public Sub DoCalculation() Implements NewMegaCalc2.IMegaCalc.doCalculation
Dim IValue As Integer
mdblMean = 0
If (mintValue = 0) Then Exit Sub
For IValue = 0 To mintValue - 1 Step 1
mdblMean = mdblMean + mdblValues(IValue)

Next
mdblMean = mdblMean / IValue

End Sub

Public Function GetOutput() As Double Implements NewMegaCalc2.IMegaCalc.GetOutput
GetOutput = mdblMean
End Function

Public Sub Reset() Implements NewMegaCalc2.IMegaCalc.Reset
mintValue = 0
End Sub

Public Sub New()
Reset()
End Sub
End Class

******************************
PreRequesite:
1)create a vb.net class library called NewMeanCalc2 add following code to it
2)build project

Public Class Class1


End Class
Public Interface IMegaCalc
Sub Addinput(ByVal InputValue As Double)
Sub doCalculation()
Function GetOutput() As Double
Sub Reset()
End Interface

OBJECT SERIALIZATION IN C#:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using objectStore;
namespace Object_serialization_in_Csharp
{
class Program
{
static void Main(string[] args)
{
try
{
List products = new List();
products.Add(new Product(1,"LaysSpicy",15,"Timepass"));
products.Add(new Product(2, "Kurkure", 10,"GupShupParty"));
products.Add(new Product(3, "Cadbary", 10, "Sweet Treat"));
products.Add(new Product(4, "Edli", 7, "snacks"));
products.Add(new Product(5, "James", 15, "Kid'sFavourite"));

Console.WriteLine("Product to save");
foreach (Product product in products)
{
Console.WriteLine(product);
}
Console.WriteLine();

//get serializer
IFormatter serializer = new BinaryFormatter();

//serialize product
FileStream saveFile = new FileStream("Product.bin",FileMode.OpenOrCreate, FileAccess.Write );
serializer.Serialize(saveFile,products);
saveFile.Close();


//De serialize
FileStream loadFile = new FileStream("Product.bin", FileMode.Open, FileAccess.Read);
List savedProducts = serializer.Deserialize(loadFile) as List;
loadFile.Close();
Console.WriteLine("Products Loaded");

foreach (Product product in savedProducts)
{
Console.WriteLine(product);
}
}
catch(SerializationException e)
{
Console.WriteLine(e.Message);
}
finally
{

}
Console.ReadKey();
}
}
}
namespace objectStore
{
public class Product
{
public long Id;
public string Name;
public double Price;
[NonSerialized]
string Notes;
public Product(long id, string name, double price, string notes)
{
Id = id;
Name = name;
Price = price;
Notes = notes;
}
public override string ToString()
{
string str;
Str = "ID: " + Id + " Name: " + Name + " Price: " +
Price.ToString() + " Notes: " + Notes;
return str;
}
}
}

Using ImageMap Server Control with C#:



HTML:

%@ 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">
<title>ImageMap server Control</title>
</head>

<body>
<form id="form1" runat="server">
<div>

<asp:ImageMap ID="ImageMap1" runat="server" ImageUrl="~/Images/daisy.jpg"
HotSpotMode="PostBack" Width="200" onclick="ImageMap1_Click" Height="200">

<asp:RectangleHotSpot Top="0" Bottom="100" Right="100" Left="0" AlternateText="Purnima" PostBackValue="purnima"/>
<asp:RectangleHotSpot Top="0" Bottom="100" Right="200" Left="100" AlternateText="Pratiksha" PostBackValue="pratiksha"/>
<asp:RectangleHotSpot Top="100" Bottom="200" Right="100" Left="0" AlternateText="Suverna" PostBackValue="suverna"/>
<asp:RectangleHotSpot Top="100" Bottom="200" Left="100" Right="200" AlternateText="Sajida" PostBackValue="sajida"/>
</asp:ImageMap>

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

C# Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

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

}
protected void ImageMap1_Click(object sender, ImageMapEventArgs e)
{
Response.Write(e.PostBackValue.ToString());
}
}

C# Implementation of Writing Data to XML Format using Dataset

C# Implementation of Writing Data to XML Format using Dataset’s :WriteXml method:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml ;
namespace Writing_To_XML
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Initial Catalog=sangram;Data Source=(Local)");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from course", con);
SqlCommandBuilder sbuilder = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "course");
da = new SqlDataAdapter("select * from student", con);
da.Fill(ds,"student");

//setting relation between cno field common to both

DataRelation dataRel=ds.Relations.Add("RelName",ds.Tables[0].Columns["cno"],ds.Tables[1].Columns["cno"]);
dataRel.Nested=true ;
ds.WriteXml(@"I:\Trial\CourseStud.xml");
Console.WriteLine("Program Execution Finished:");
con.Close();
Console.ReadKey();
}
}

}



Working With DataList Control Templates:



C# code:

using System;
using System.Data;
using System.Data.SqlClient;
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;

public partial class _Default : System.Web.UI.Page
{
static DataSet ds;
static SqlDataAdapter da;
static SqlCommandBuilder cmdBuilder;
static string currentCno;

protected void Page_Load(object sender, EventArgs e)
{
if (! Page.IsPostBack)
{
Bind();
}

}
public void Bind()
{
SqlConnection con = new SqlConnection("Initial Catalog=sangram;Integrated Security=SSPI;Data Source=(local);");
con.Open();
da = new SqlDataAdapter("select * from courses", con);
cmdBuilder = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds, "courses");
DataList1.DataSource = ds.Tables[0];
DataList1.DataBind();
}

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{


if (e.CommandName == "Select")
{
DataList1.SelectedIndex = e.Item.ItemIndex;
currentCno = ((Label)e.Item.FindControl("LblCourseId")).Text;
Bind();
}
if (e.CommandName == "Insert")
{
string cno = ((TextBox)e.Item.FindControl("TxtCourseId")).Text;
string cname = ((TextBox)e.Item.FindControl("TxtCourseName")).Text;
string duration = ((TextBox)e.Item.FindControl("TxtCourseDuration")).Text;
string fees = ((TextBox)e.Item.FindControl("TxtCourseFees")).Text;

DataColumn[] Dcol = new DataColumn[1];
Dcol[0] = ds.Tables[0].Columns[0];
ds.Tables[0].PrimaryKey = Dcol;

DataRow drow;
drow = ds.Tables[0].NewRow();

drow[0] = cno;
drow[1] = cname;
drow[2] = duration;
drow[3] = fees;

ds.Tables[0].Rows.Add(drow);

da.Update(ds, "Courses");

Bind();

}


}
protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = -1;
DataList1.SelectedIndex = -1;
Bind();
}
protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
// Retrieve the updated values from the selected item.
string cno =((TextBox) e.Item.FindControl("TxtCourseId")).Text;
string cname =((TextBox) e.Item.FindControl("TxtCourseName")).Text;
string duration =((TextBox) e.Item.FindControl("TxtCourseDuration")).Text;
string fees =((TextBox) e.Item.FindControl("TxtCourseFees")).Text;


//Adding Temp prim key
DataColumn[] Dcol=new DataColumn[1];
Dcol[0]=ds.Tables[0].Columns[0];
ds.Tables[0].PrimaryKey = Dcol;

DataRow drow ;
if (ds.Tables[0].Rows.Find(cno)!= null)
{
//modifing exiting row without changing cno
drow = ds.Tables[0].Rows.Find(cno);

drow[0] =cno;
drow[1] = cname;
drow[2] = duration;
drow[3] = fees;

}
else
{
//deleting old row
ds.Tables[0].Rows.Find(currentCno).Delete();
//adding new row
drow = ds.Tables[0].NewRow();
drow[0] =cno;
drow[1] = cname;
drow[2] = duration;
drow[3] = fees;

ds.Tables[0].Rows.Add(drow);
}

//updating deleted row and newly added row simultenously
da.Update(ds, "Courses");


DataList1.EditItemIndex = -1;
DataList1.SelectedIndex = -1;

Bind();

}
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
Bind();
}
protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
{
//Adding Temp prim key
DataColumn[] Dcol = new DataColumn[1];
Dcol[0] = ds.Tables[0].Columns[0];
ds.Tables[0].PrimaryKey = Dcol;

string cno = ((TextBox)e.Item.FindControl("TxtCourseId")).Text;

ds.Tables[0].Rows.Find(cno).Delete();
da.Update(ds, "Courses");
Bind();
}
public int GetMaxCno()
{

DataRow[] drow= ds.Tables[0].Select("cno=max(cno)");
string maxRow = drow[0][0].ToString();
return Convert.ToInt16( maxRow);
}

}

HTML:

<%@ 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">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand" OnCancelCommand="DataList1_CancelCommand" OnUpdateCommand="DataList1_UpdateCommand" OnEditCommand="DataList1_EditCommand" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" OnDeleteCommand="DataList1_DeleteCommand" >
<HeaderTemplate>
<table style="border-style:solid;">
<tr>
<td >Course Id</td>
<td>Course Name</td>
<td>Course Duration</td>
<td>Course Fees</td>
<td>Command</td>
</tr>

</HeaderTemplate>
<FooterTemplate>
<tr>
<td><asp:TextBox ID="TxtCourseId" Enabled="false" Text='<%#GetMaxCno()+1%>' runat="server"></asp:TextBox></td>
<td><asp:TextBox ID="TxtCourseName" Text="CourseName" runat="server"></asp:TextBox></td>
<td><asp:TextBox ID="TxtCourseDuration" Text="CourseDuration" runat="server"></asp:TextBox></td>
<td><asp:TextBox ID="TxtCourseFees" Text="CourseFees" runat="server"></asp:TextBox></td>
<td><asp:Button ID="Btn3" Text="Insert" CommandName="Insert" runat="server" /></td>
</tr>
</table>
</FooterTemplate>

<ItemTemplate>
<tr>
<td>
<asp:Label ID="LblCourseId" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ></asp:Label>
</td>
<td>
<asp:Label ID="LblCourseName" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ></asp:Label>
</td>
<td>
<asp:Label ID="LblCourseDuration" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ></asp:Label>
</td>
<td>
<asp:Label ID="LblCourseFees" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ></asp:Label>
</td>
<td>
<asp:Button ID="Button1" runat="server" CommandName="Select" Text="Select"></asp:Button >
</td>
</tr>

</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color:Burlywood;">
<td>
<asp:Label ID="LblCourseId" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ></asp:Label>
</td>
<td>
<asp:Label ID="LblCourseName" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ></asp:Label>
</td>
<td>
<asp:Label ID="LblCourseDuration" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ></asp:Label>
</td>
<td>
<asp:Label ID="LblCourseFees" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ></asp:Label>
</td>
<td>
<asp:Button ID="Btn1" runat="server" CommandName="Select" Text="Select"></asp:Button>
</td>
</tr>
</AlternatingItemTemplate>
<SelectedItemTemplate>
<tr>
<td>
<asp:TextBox ID="TxtCourseId" Enabled="false" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno")%>/>
</td>
<td>
<asp:TextBox ID="TxtCourseName" Enabled="false" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname")%>/>
</td>
<td>
<asp:TextBox ID="TxtCourseDuration" Enabled="false" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> />
</td>
<td>
<asp:TextBox ID="TxtCourseFees" runat="server" Enabled="false" Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> />
</td>
<td>
<asp:Button ID="Btn1" runat="server" CommandName="Edit" Text="Edit"></asp:Button >
</td>
<td>
<asp:Button ID="Btn2" runat="server" CommandName="Delete" Text="Delete"></asp:Button >
</td>
</tr>
</SelectedItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="TxtCourseId" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno")%>/>
</td>
<td>
<asp:TextBox ID="TxtCourseName" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname")%>/>
</td>
<td>
<asp:TextBox ID="TxtCourseDuration" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> />
</td>
<td>
<asp:TextBox ID="TxtCourseFees" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> />
</td>
<td>
<asp:Button ID="Btn1" runat="server" CommandName="Update" Text="Update"></asp:Button >
</td>
<td>
<asp:Button ID="Btn2" runat="server" CommandName="Cancel" Text="Cancel"></asp:Button >
</td>
</tr>
</EditItemTemplate>

</asp:DataList></div>
</form>
</body>
</html>

using query string

ASP.NET 2.0

Create a new webApplication .Add Following Code to it


Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim UserName As String
UserName = Request.QueryString("Name")
Response.Write("Hello" + " " + UserName + " Have a nice day!")
End Sub
End Class

Now to test it:
Open Internet Explorer in Address Bar write address of our aspx page
followed by ? Name=Sangram.
Add Press Go.

You will see on web form “Hello Sangram have a nice day!”.

Using Mysql with C#.NET:



Pre-Requiste:
1)create a datbase in mysql with name say ‘sangram’
2)create atable in it namely ‘course’ with columns ‘cno’ as in and ‘cname as varchar(20)
3) add some record into it
4) now create c# window application with datagridview and to command button one for loading data other for exiting application
5) put following code

CodeBehind :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace mysqldemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void LoadGuests()
{
try
{
//create a new mysqlconnection
MySqlConnection mycon=new MySqlConnection("datasource=localhost;username=root;password=root;database=sangram");
mycon.Open();

//creating mysql adapter
MySqlDataAdapter myadp = new MySqlDataAdapter("select * from course", mycon);

//create dataset
DataSet myds = new DataSet();

//now fill and bind the datagrid
myadp.Fill(myds, "course");
dataGridView1.DataSource = myds.Tables["course"].DefaultView;



}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}

}

private void button2_Click(object sender, EventArgs e)
{
this.Close();
}

private void button1_Click(object sender, EventArgs e)
{
LoadGuests();
}

}
}

Using Gridview Template:



HTML:

<%@ 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">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Cno">

<ItemTemplate>
<asp:Label ID="LblCno" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno") %> BorderStyle="Solid"></asp:Label>
</ItemTemplate>

<AlternatingItemTemplate>
<asp:Label ID="LblCno" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno") %> BorderStyle="Solid" BackColor="yellow"></asp:Label>
</AlternatingItemTemplate>

<EditItemTemplate>
<asp:TextBox runat="server" ID="TxtCno" Text=<%#DataBinder.Eval(Container.DataItem,"cno") %>></asp:TextBox>
</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Cname">

<ItemTemplate>
<asp:Label ID="LblCname" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname") %> BorderStyle="Solid"></asp:Label>
</ItemTemplate>

<AlternatingItemTemplate>
<asp:Label ID="LblCname" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname") %> BorderStyle="Solid" BackColor="yellow"></asp:Label>
</AlternatingItemTemplate>

<EditItemTemplate>
<asp:TextBox runat="server" ID="TxtCname" Text=<%#DataBinder.Eval(Container.DataItem,"cname") %>></asp:TextBox>
</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Duration">

<ItemTemplate>
<asp:Label ID="LblDuration" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration") %> BorderStyle="Solid"></asp:Label>
</ItemTemplate>

<AlternatingItemTemplate>
<asp:Label ID="LblDuration" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration") %> BorderStyle="Solid" BackColor="yellow"></asp:Label>
</AlternatingItemTemplate>

<EditItemTemplate>
<asp:TextBox runat="server" ID="TxtDuration" Text=<%#DataBinder.Eval(Container.DataItem,"duration") %>></asp:TextBox>
</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Fees">

<ItemTemplate>
<asp:Label ID="LblFees" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"fees") %> BorderStyle="Solid"></asp:Label>
</ItemTemplate>

<AlternatingItemTemplate>
<asp:Label ID="LblFees" runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"fees") %> BorderStyle="Solid" BackColor="yellow"></asp:Label>
</AlternatingItemTemplate>

<EditItemTemplate>
<asp:TextBox runat="server" ID="TxtFees" Text=<%#DataBinder.Eval(Container.DataItem,"fees") %>></asp:TextBox>
</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Command">

<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Edit" CommandArgument=<%#cursor++ %> CommandName="Edit"></asp:button>
</ItemTemplate>

<AlternatingItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Edit" BackColor="yellow" CommandArgument=<%#cursor++ %> CommandName="Edit"></asp:button>
</AlternatingItemTemplate>

<EditItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Update" CommandArgument=<%#cursor++ %> CommandName="Update"></asp:button>
<asp:Button ID="Btn2" runat="server" Text="Cancel" CommandArgument=<%#cursor++ %> CommandName="Cancel"></asp:button>
</EditItemTemplate>

</asp:TemplateField>
</Columns>

</asp:GridView>
<asp:Label ID="LblMessage" runat="server"></asp:Label></div>
</form>
</body>
</html>


C#:
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.Data.SqlClient;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
public static int cursor;
public static string[] OldRowValues;
public static string[] NewRowValues;
public static SqlDataAdapter da;
public static DataSet ds;
public static SqlCommandBuilder cmdBuilder;
public static SqlConnection con;

protected void Page_Load(object sender, EventArgs e)
{
if (! Page.IsPostBack)
{
OldRowValues = new string[4];
NewRowValues = new string[4];
cursor = 0;
Bind();
}

}
public void Bind()
{
con = new SqlConnection("Initial Catalog=sangram;Integrated Security=SSPI;Data Source=(local);");
con.Open();
da = new SqlDataAdapter("select * from courses", con);
cmdBuilder = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds, "Courses");

DataColumn[] dcol = new DataColumn[1];
dcol[0] = ds.Tables[0].Columns[0];
ds.Tables[0].PrimaryKey = dcol;

GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow row = GridView1.Rows[e.NewEditIndex];

for (int i = 0; i < row.Cells.Count; i++)
{
foreach (object obj in row.Cells[i].Controls)
{
if (obj is Label)
{

OldRowValues[i] = ((Label)obj).Text;
}
}
}
//code to update data


GridView1.EditIndex = e.NewEditIndex;
Bind();


}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.SelectedIndex = -1;
e.Cancel = true;
Bind();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = e.RowIndex;
GridViewRow row = GridView1.Rows[e.RowIndex];

for (int i = 0; i < row.Cells.Count; i++)
{
foreach (object obj in row.Cells[i].Controls)
{
if (obj is TextBox)
{
NewRowValues[i] = ((TextBox)obj).Text;
}

}
}

if (NewRowValues[0] == OldRowValues[0])
{
//need only to update
DataRow drow = ds.Tables[0].Rows.Find(OldRowValues[0]);

drow[0] = NewRowValues[0];
drow[1] = NewRowValues[1];
drow[2] = NewRowValues[2];
drow[3] = NewRowValues[3];

da.Update(ds, "Courses");

}
else
{
//need deletion of initial row
ds.Tables[0].Rows.Find(OldRowValues[0]).Delete();

//insertion of new row
DataRow drow = ds.Tables[0].NewRow();
drow[0] = NewRowValues[0];
drow[1] = NewRowValues[1];
drow[2] = NewRowValues[2];
drow[3] = NewRowValues[3];

ds.Tables[0].Rows.Add(drow);

da.Update(ds, "Courses");
}

GridView1.EditIndex = -1;
GridView1.SelectedIndex = -1;
Bind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

}
}

Using DataList Control Template



C#:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
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;

public partial class Default2 : System.Web.UI.Page
{
static DataSet ds;
static SqlDataAdapter da;
static SqlCommandBuilder cmdBuilder;
static string currentCno;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Bind();
}
}
public void Bind()
{
SqlConnection con = new SqlConnection("Initial Catalog=sangram;Integrated Security=SSPI;Data Source=(local);");
con.Open();
da = new SqlDataAdapter("select * from courses", con);
cmdBuilder = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds, "courses");
Repeater1.DataSource = ds.Tables[0];
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Select")
{

MessageLabel.Text ="You Have Selected Course In: " + ds.Tables[0].Rows[e.Item.ItemIndex][1].ToString() ;

}
}
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
MessageLabel.Text = "All Items Have Been Created";
}
}

HTML :
<%@ 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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand" OnItemCreated="Repeater1_ItemCreated">
<HeaderTemplate>
<table>
<tr>
<td><strong>Id</strong></td>
<td><strong>Course Name</strong></td>
<td><strong>Course Duration</strong></td>
<td><strong>Fees</strong></td>
<td><strong>Command</strong></td>
</tr>
</HeaderTemplate>

<FooterTemplate>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</FooterTemplate>

<ItemTemplate>
<tr>
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ID="LblCourseId"></asp:Label></td>
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ID="LblCourseName"></asp:Label></td>
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ID="LblCourseDuration"></asp:Label></td>
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ID="LblCourseFees"></asp:Label></td>
<td><asp:Button ID="Btn1" Text="Select" CommandName="Select" runat="server" /> </td>
</tr>
</ItemTemplate>

<AlternatingItemTemplate>
<tr style="background-color:Burlywood;">
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ID="LblCourseId"></asp:Label></td>
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ID="LblCourseName"></asp:Label></td>
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ID="LblCourseDuration"></asp:Label></td>
<td><asp:Label runat="server" Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ID="LblCourseFees"></asp:Label></td>
<td><asp:Button ID="Btn1" Text="Select" CommandName="Select" runat="server" /> </td>
</tr>
</AlternatingItemTemplate>
</asp:Repeater>
<br />
<asp:Label ID="MessageLabel" runat="server"></asp:Label></div>
</form>
</body>
</html>

Updating Existing Record using Dataset & CommandBuilder Object in C#:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace Updating_Dataset
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Initial Catalog=sangram;Data Source=(local)");
SqlDataAdapter da = new SqlDataAdapter("select * from course", con);
SqlCommandBuilder sbuilder = new SqlCommandBuilder(da);
DataSet ds = new DataSet();

da.Fill(ds, "course");
Console.WriteLine("Old Row:");
Console.Write(ds.Tables["course"].Rows[0][0].ToString());
Console.Write(" "+ ds.Tables["course"].Rows[0][1].ToString());
Console.Write(" " + ds.Tables["course"].Rows[0][2].ToString());
Console.Write(" "+ds.Tables["course"].Rows[0][3].ToString());

ds.Tables[0].Rows[0][1] = "GW BASIC";
da.Update(ds, "course");

Console.WriteLine("Edited Row:");
Console.Write(ds.Tables["course"].Rows[0][0].ToString());
Console.Write(" " + ds.Tables["course"].Rows[0][1].ToString());
Console.Write(" " + ds.Tables["course"].Rows[0][2].ToString());
Console.Write(" " + ds.Tables["course"].Rows[0][3].ToString());

Console.ReadKey();
con.Close();
}
}
}

Tranferring data from sql server to ms Access with C#:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;

namespace MSACCESS
{
class Program
{
static void Main(string[] args)
{
string strDestPath = "I:\\Trial\\school.mdb";
SqlConnection sqlcon=new SqlConnection("Data Source=(Local);Integrated Security=SSPI;Initial Catalog=sangram") ;
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("select * from course", sqlcon);
SqlDataReader sqldr = sqlcmd.ExecuteReader();
LoadFromSql(sqldr,strDestPath,"course");
Console.ReadKey();
}

private static void LoadFromSql(SqlDataReader dr1, string Path,string table)
{
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;Data Source = " + Path );
olecon.Open();

OleDbCommand olecmd = new OleDbCommand();
olecmd.Connection = olecon;

string strCno,strCname,strDuration,strFees;

while (dr1.Read())
{
string strCmd;

strCno=dr1[0].ToString();
strCname = dr1[1].ToString();
strDuration = dr1[2].ToString();
strFees = dr1[3].ToString();

strCmd = "Insert into course values(" + strCno + ",'" + strCname+ "'," + strDuration+ "," + strFees + ")";
olecmd.CommandText = strCmd;

try
{
olecmd.ExecuteNonQuery();
}
catch( OleDbException oleEx)
{
Console.WriteLine(oleEx.Message);
}

}


}
}
}

Reading Sql Data using Adapter & Dataset With C#:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace DATASET_Handling
{
class Program
{
static void Main(string[] args)
{
SqlConnection sqlcon = new SqlConnection("Integrated Security= SSPI;Initial Catalog=sangram;Data Source=(Local) ");
sqlcon.Open();

SqlDataAdapter sqlda = new SqlDataAdapter("select * from course", sqlcon);
DataSet ds = new DataSet();

sqlda.Fill(ds, "course");

foreach (DataRow drow in ds.Tables["course"].Rows )
{
Console.Write("Cno:"+ drow["cno"].ToString());
Console.Write(" Cname:"+ drow["cname"]);
Console.Write(" Duration:" + drow["duration"].ToString());
Console.Write(" Fees:"+ drow["fees"].ToString());
Console.WriteLine();
}
sqlcon.Close();
Console.WriteLine("Program Finished");
Console.ReadKey();

}
}
}

Reading MSSQL data using datareader ,command object,connection object & writing the data to plane text file:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SqlClient;


namespace writing_data_to_text_file_in_csharp
{
class Program
{

static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=(Local);Initial Catalog = Sangram;Integrated Security=SSPI");
con.Open();

SqlCommand cmd = new SqlCommand("select * from course", con);
SqlDataReader dr = cmd.ExecuteReader();

string strPath ="I:\\trial\\Course.txt";
//writing data to text file
writeToFile(dr,strPath);

//releases datareader object
dr.Close();
dr.Dispose();

//releases connection object
con.Close();
con.Dispose();

//releases command object
cmd.Dispose();

}

private static void writeToFile(SqlDataReader dr1,string Path)
{

FileStream fstream= new FileStream(Path , FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter swriter= new StreamWriter(fstream);

while(dr1.Read())
{
string textrow;
textrow = dr1["cno"].ToString();
textrow = textrow+ " " + dr1["cname"];
textrow = textrow + " " + dr1["duration"].ToString();
textrow = textrow + " " + dr1["fees"].ToString();
swriter.WriteLine(textrow);
}
swriter.Close();
swriter.Dispose();

fstream.Close();
fstream.Dispose();

dr1.Close();
dr1.Dispose();
}
}

}

MYSQL & C# 2

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace Mysql2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection con = new MySqlConnection("datasource=localhost;username=root;password=indusstar;database=mysql");
con.Open();

MySqlDataAdapter da = new MySqlDataAdapter("select * from courses", con);
//need table with primary key
MySqlCommandBuilder cmdBuilder = new MySqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "courses");

DataRow drow = ds.Tables[0].Rows[3];

//updating

drow[0] = 4;
drow[1] = "Gambas.Net";
drow[2] = 5;
drow[3] = 8000;

da.Update(ds, "courses");

con.Close();

}
}
}

MYSQL 5 & C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace Mysql2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection con = new MySqlConnection("datasource=localhost;username=root;password=indusstar;database=mysql");
con.Open();

MySqlDataAdapter da = new MySqlDataAdapter("select * from courses", con);
//need table with rimary key
MySqlCommandBuilder cmdBuilder = new MySqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "courses");

DataRow drow = ds.Tables[0].NewRow();
drow[0] = 4;
drow[1] = "Gambas";
drow[2] = 3;
drow[3] = 5000;

ds.Tables[0].Rows.Add(drow);
da.Update(ds, "courses");

con.Close();

}
}
}

Populating Dataset with 2 tables in C#:



using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Adapter_Dataset
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Integrated security=SSPI;Initial Catalog=sangram;Data source=(local)");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from course", con);
DataSet ds = new DataSet();
da.Fill(ds,"course");
da = new SqlDataAdapter("select * from student", con);
da.Fill(ds, "student");

Console.WriteLine("Course Table");
foreach (DataRow drow in ds.Tables["course"].Rows)
{
Console.Write("Cno:"+ drow[0].ToString());
Console.Write(" Cname:"+ drow[1]);
Console.Write(" Duration:"+ drow[2].ToString());
Console.Write(" Fees:"+drow[3].ToString());
Console.WriteLine();
}

Console.WriteLine("Student Table");
foreach (DataRow drow in ds.Tables["student"].Rows)
{
Console.Write("Sno:"+drow[0].ToString());
Console.Write(" Sname:"+ drow[1]);
Console.Write(" Cno:"+ drow[2].ToString());
Console.WriteLine();
}
Console.ReadKey();

}
}
}

Inserting Record into Existing DataBase using commandbuilber,datarow,Adapter:




using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace Adding_Rows_to_table
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Initial Catalog=sangram;Data Source=(local)");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from course", con);
SqlCommandBuilder sbuilder = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "course");
Console.WriteLine("Number of Rows Before Adding New Record :" + ds.Tables[0].Rows.Count.ToString());

DataRow drow = ds.Tables[0].NewRow();

drow["cno"] = 27;
drow["cname"] = "CORE JAVA";
drow["duration"] = 2;
drow["fees"] = 4000 ;

ds.Tables[0].Rows.Add(drow);
da.Update(ds, "course");

Console.WriteLine(ds.Tables[0].Rows.Count.ToString());

con.Close();
Console.ReadKey();

}
}
}

GridView Control



C# Code:

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.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
public static SqlConnection con;
public static SqlDataAdapter da;
public static SqlCommandBuilder cmdBuilder;
public static DataSet ds;
public static int SelectedRowIndex;
public static DataTable DTable;

public static string[] OldRowValue;
public static string[] NewRowValue;

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack==false)
{
SelectedRowIndex = 0;
OldRowValue = new string[4];
NewRowValue = new string[4];
BindGrid();
ToggleSelectCol(true, false, false,false);
}
}

public void ToggleSelectCol(bool status1,bool status2,bool status3,bool status4)
{
GridView1.Columns[5].Visible =status1;
GridView1.Columns[6].Visible = status2;
GridView1.Columns[7].Visible = status3;
GridView1.Columns[8].Visible = status4;
}

public void BindGrid()
{
//pulling records from database
con = new SqlConnection("Initial Catalog=sangram;Integrated Security=SSPI;Data Source=(local)");
con.Open();
ds = new DataSet();
da = new SqlDataAdapter("select * from courses", con);
da.Fill(ds, "courses");

//setting commandbuilder
cmdBuilder = new SqlCommandBuilder(da);

//Adding Temp col in database
DataColumn dcol = new DataColumn();
dcol.DataType=System.Type.GetType("System.String");
dcol.AllowDBNull = false;
dcol.Caption = "Index";
dcol.ColumnName = "Index";

ds.Tables[0].Columns.Add(dcol);

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow drow = ds.Tables[0].Rows[i];
drow["Index"] = i.ToString();
}
//Adding Primary key
AddPrimaryKey();

//binding data to gridview
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

}

public void SlashColFromDataset()
{
DTable = new DataTable();
DTable = ds.Tables[0];
LblMessage.Text = "Original Table:" + ds.Tables[0].Columns.Count.ToString();
LblMessage.Text = LblMessage.Text + "New Table:" + DTable.Columns.Count.ToString();
DTable.Columns.Remove("Index");
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
SelectedRowIndex = Convert.ToInt16(e.CommandArgument);
GridView1.SelectedIndex = SelectedRowIndex;

//
DisableRow(false,true);
ToggleSelectCol(false,true,true,true);

//collecting old Values
GetOldValues();
//slash index col from table
SlashColFromDataset();

}
if (e.CommandName == "Insert")
{

}
if(e.CommandName=="CancelSelect")
{
GridView1.SelectedIndex = -1;
ToggleSelectCol(true, false, false, false);
DisableRow(true, true);
BindGrid();
}
if (e.CommandName == "Delete")
{
ToggleSelectCol(true,false,false,false);
DisableRow(true,true);
DeleteRecord();
BindGrid();
}

if (e.CommandName == "Edit")
{
GridView1.EditIndex = SelectedRowIndex;
BindGrid();

//other row remain in disable state
DisableRow(false, true);

//changing visiblity of col that doesn't apply
ToggleSelectCol(false, true, false,false);

//seting index of item to edit

}

if (e.CommandName == "Cancel")
{
ToggleSelectCol(true, false, false,false);
DisableRow(true, true);
GridView1.SelectedIndex = -1;
GridView1.EditIndex = -1;
BindGrid();

}

if (e.CommandName == "Update")
{
ToggleSelectCol(true, false, false,false);
DisableRow(true, true);


//collecting modified values
GetNewValue();

//Reflecting changes to database
if (NewRowValue[0] == OldRowValue[0])
{
UpdateRecord();
}
else
{
//need deletion of old row
DeleteRecord();
//insertion of new row
InsertRecord();

}


}
}
public void AddPrimaryKey()
{
DataColumn[] dcol = new DataColumn[1];
dcol[0] = ds.Tables[0].Columns[0];
ds.Tables[0].PrimaryKey = dcol;
}

public void DisableRow(bool other,bool selected)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].Enabled = other ;
}
if (selected == true)
{
GridView1.Rows[SelectedRowIndex].Enabled = selected;
}
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView1.SelectedIndex = -1;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.SelectedIndex = -1;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

GridView1.EditIndex = -1;
GridView1.SelectedIndex = -1;
BindGrid();
}
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{

}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{


}

public void GetNewValue()
{
GridViewRow Row = GridView1.Rows[SelectedRowIndex];
int i = 0;
for (int j = 1; j < 5; j++)
{
foreach (object obj in Row.Cells[j].Controls)
{
if (obj is TextBox)
{
TextBox Txt = (TextBox)obj;
NewRowValue[i] = Txt.Text;
i++;
}
}
}
}

public void GetOldValues()
{
GridViewRow Row = GridView1.Rows[SelectedRowIndex];
int i = 0;
//As very first row is of Index not actually in database
for (int j = 1; j < 5; j++)
{
foreach (object obj in Row.Cells[j].Controls)
{
if (obj is Label)
{
Label Lbl = (Label)obj;
OldRowValue[i] = Lbl.Text;
i++;
}
}
}

}

public void UpdateRecord()
{
if (NewRowValue[0] == OldRowValue[0])
{
DataRow DRow = DTable.Rows.Find(OldRowValue[0]);
//need updating
for (int i = 0; i < 4; i++)
{
DRow[i] = NewRowValue[i];
}

//Updating DataAdapter
da.Update(DTable);
}
}

public void DeleteRecord()
{
//deleting selected row
DTable.Rows[SelectedRowIndex].Delete();

//Need to reflect changes in database
da.Update(DTable);
}

public void InsertRecord()
{
DataRow Drow = DTable.NewRow();

for (int i = 0; i < 4; i++)
{
Drow[i] = NewRowValue[i];
}
DTable.Rows.Add(Drow);
//Updating DataAdapter once for deletion and insertion
da.Update(DTable);
}
}

HTML CODE:

<%@ 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">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdated="GridView1_RowUpdated" OnRowUpdating="GridView1_RowUpdating" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Height="177px" Width="516px" >
<SelectedRowStyle BackColor="Aqua" />
<Columns>

<asp:TemplateField HeaderText="Index">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"index")%> ID="LblIndex" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>


<asp:TemplateField HeaderText="Course Id">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ID="LblCno" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ID="EditTxtCno" runat="server"></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox Text="" ID="InsertTxtCno" runat="server"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Course Name">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ID="LblCname" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ID="EditTxtCname" runat="server"></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox Text="" ID="InsertTxtCname" runat="server"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Course Duration">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ID="LblDuration" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ID="EditTxtDuration" runat="server"></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox Text="" ID="InsertTxtDuration" runat="server"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Course Fees">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ID="LblFees" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ID="EditTxtFees" runat="server"></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox Text="" ID="InsertTxtFees" runat="server"></asp:TextBox>
</InsertItemTemplate>

</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnSelect" Text="Select" CommandName="Select" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnEdit" Text="Edit" CommandName="Edit" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" Text="Update" CommandName="Update" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
<asp:Button ID="BtnCancel" Text="Cancel" CommandName="Cancel" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Btndelete" Text="Delete" CommandName="Delete" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnCancelSelect" Text="Cancel Select" CommandName="CancelSelect" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnInsert" Text="Insert" CommandName="Insert" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="LblMessage" runat="server"></asp:Label></div>
</form>
</body>
</html>

GridView Control Template:



HTML Code:

<%@ 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">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdated="GridView1_RowUpdated" OnRowUpdating="GridView1_RowUpdating" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Height="177px" Width="516px" >
<SelectedRowStyle BackColor="Aqua" />
<Columns>

<asp:TemplateField HeaderText="Index">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"index")%> ID="LblIndex" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>


<asp:TemplateField HeaderText="Course Id">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ID="LblCno" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"cno")%> ID="EditTxtCno" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Course Name">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ID="LblCname" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"cname")%> ID="EditTxtCname" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Course Duration">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ID="LblDuration" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"duration")%> ID="EditTxtDuration" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Course Fees">
<ItemTemplate>
<asp:Label Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ID="LblFees" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text=<%#DataBinder.Eval(Container.DataItem,"fees")%> ID="EditTxtFees" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnSelect" Text="Select" CommandName="Select" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnEdit" Text="Edit" CommandName="Edit" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" Text="Update" CommandName="Update" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
<asp:Button ID="BtnCancel" Text="Cancel" CommandName="Cancel" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Btndelete" Text="Delete" CommandName="Delete" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnCancelSelect" Text="Cancel Select" CommandName="CancelSelect" runat="server" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"index")%> />
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

C# Code:
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.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
public static SqlConnection con;
public static SqlDataAdapter da;
public static SqlCommandBuilder cmdBuilder;
public static DataSet ds;
public static int SelectedRowIndex;
public static DataTable DTable;

public static string[] OldRowValue;
public static string[] NewRowValue;

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack==false)
{
SelectedRowIndex = 0;
OldRowValue = new string[4];
NewRowValue = new string[4];
BindGrid();
ToggleSelectCol(true, false, false,false);
}
}

public void ToggleSelectCol(bool status1,bool status2,bool status3,bool status4)
{
GridView1.Columns[5].Visible =status1;
GridView1.Columns[6].Visible = status2;
GridView1.Columns[7].Visible = status3;
GridView1.Columns[8].Visible = status4;
}

public void BindGrid()
{
//pulling records from database
con = new SqlConnection("Initial Catalog=sangram;Integrated Security=SSPI;Data Source=(local)");
con.Open();
ds = new DataSet();
da = new SqlDataAdapter("select * from courses", con);
da.Fill(ds, "courses");

//setting commandbuilder
cmdBuilder = new SqlCommandBuilder(da);

//Adding Temp col in database
DataColumn dcol = new DataColumn();
dcol.DataType=System.Type.GetType("System.String");
dcol.AllowDBNull = false;
dcol.Caption = "Index";
dcol.ColumnName = "Index";

ds.Tables[0].Columns.Add(dcol);

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow drow = ds.Tables[0].Rows[i];
drow["Index"] = i.ToString();
}
//Adding Primary key
AddPrimaryKey();

//binding data to gridview
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

}

public void SlashColFromDataset()
{
DTable = new DataTable();
DTable = ds.Tables[0];


DTable.Columns.Remove("Index");
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
SelectedRowIndex = Convert.ToInt16(e.CommandArgument);
GridView1.SelectedIndex = SelectedRowIndex;

//
DisableRow(false,true);
ToggleSelectCol(false,true,true,true);

//collecting old Values
GetOldValues();
//slash index col from table
SlashColFromDataset();

}

if(e.CommandName=="CancelSelect")
{
GridView1.SelectedIndex = -1;
ToggleSelectCol(true, false, false, false);
DisableRow(true, true);
BindGrid();
}
if (e.CommandName == "Delete")
{
ToggleSelectCol(true,false,false,false);
DisableRow(true,true);
DeleteRecord();
BindGrid();
}

if (e.CommandName == "Edit")
{
GridView1.EditIndex = SelectedRowIndex;
BindGrid();

//other row remain in disable state
DisableRow(false, true);

//changing visiblity of col that doesn't apply
ToggleSelectCol(false, true, false,false);

//seting index of item to edit

}

if (e.CommandName == "Cancel")
{
ToggleSelectCol(true, false, false,false);
DisableRow(true, true);
GridView1.SelectedIndex = -1;
GridView1.EditIndex = -1;
BindGrid();

}

if (e.CommandName == "Update")
{
ToggleSelectCol(true, false, false,false);
DisableRow(true, true);


//collecting modified values
GetNewValue();

//Reflecting changes to database
if (NewRowValue[0] == OldRowValue[0])
{
UpdateRecord();
}
else
{
//need deletion of old row
DeleteRecord();
//insertion of new row
InsertRecord();

}


}
}
public void AddPrimaryKey()
{
DataColumn[] dcol = new DataColumn[1];
dcol[0] = ds.Tables[0].Columns[0];
ds.Tables[0].PrimaryKey = dcol;
}

public void DisableRow(bool other,bool selected)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].Enabled = other ;
}
if (selected == true)
{
GridView1.Rows[SelectedRowIndex].Enabled = selected;
}
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView1.SelectedIndex = -1;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.SelectedIndex = -1;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

GridView1.EditIndex = -1;
GridView1.SelectedIndex = -1;
BindGrid();
}
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{

}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{


}

public void GetNewValue()
{
GridViewRow Row = GridView1.Rows[SelectedRowIndex];
int i = 0;
for (int j = 1; j < 5; j++)
{
foreach (object obj in Row.Cells[j].Controls)
{
if (obj is TextBox)
{
TextBox Txt = (TextBox)obj;
NewRowValue[i] = Txt.Text;
i++;
}
}
}
}

public void GetOldValues()
{
GridViewRow Row = GridView1.Rows[SelectedRowIndex];
int i = 0;
//As very first row is of Index not actually in database
for (int j = 1; j < 5; j++)
{
foreach (object obj in Row.Cells[j].Controls)
{
if (obj is Label)
{
Label Lbl = (Label)obj;
OldRowValue[i] = Lbl.Text;
i++;
}
}
}

}

public void UpdateRecord()
{
if (NewRowValue[0] == OldRowValue[0])
{
DataRow DRow = DTable.Rows.Find(OldRowValue[0]);
//need updating
for (int i = 0; i < 4; i++)
{
DRow[i] = NewRowValue[i];
}

//Updating DataAdapter
da.Update(DTable);
}
}

public void DeleteRecord()
{
//deleting selected row
DTable.Rows[SelectedRowIndex].Delete();

//Need to reflect changes in database
da.Update(DTable);
}

public void InsertRecord()
{
DataRow Drow = DTable.NewRow();

for (int i = 0; i < 4; i++)
{
Drow[i] = NewRowValue[i];
}
DTable.Rows.Add(Drow);
//Updating DataAdapter once for deletion and insertion
da.Update(DTable);
}
}