Wednesday, February 25, 2009

Ajax - How to Bind DropDown List

string connectionstring= "Data Source=.; Integrated Security=true; Database=realasn1;";
sqlconnection con;
SqlDataAdapter da;
Dataset ds = new Dataset();
protected void Page_Load(object sender, EventArgs e)
{
con = new (connectionstring);
con.open();
da = new SqlDataAdapter("select id,name from country", con);
ds.Clear();
da.Fill(ds);
if (!IsPostBack)
{
bindcountry(ds);
}
con.close();
}

public void bindcountry(Dataset dbset)
{
//bind office country
ddl_1.DataSource = dbset;
ddl_1.DataTextField = dbset.Tables[0].Columns[1].ToString();
ddl_1.DataValueField = dbset.Tables[0].Columns[0].ToString();
ddl_1.DataBind();
ListItem li = new ListItem();
li.Text = "--Select Country--";
li.Value = "0";
ddl_1.Items.Insert(0, li);
}

protected void ddl_1_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(500);//for update panel
if (int.Parse(ddl_1.SelectedValue) > 0)
{
con = new (connectionstring);
con.open();
da = new SqlDataAdapter("select id,name from city where countryid=" + int.Parse(ddl_1.SelectedValue) , con);
ds.Clear();
da.Fill(ds);
bindcity(ds));
}
}

public void bindcity(DataSet dbset)
{
ddl_2.DataSource = dbset;
ddl_2.DataTextField = dbset.Tables[0].Columns[1].ToString();
ddl_2.DataValueField = dbset.Tables[0].Columns[0].ToString();
ddl_2.DataBind();
ListItem li = new ListItem();
li.Text = "--Select City--";
li.Value = "0";
ddl_2.Items.Insert(0, li);
}

Labels:

ListView Groups - SampleCode

This example reads a directory in windows and list out all files in groups, for example I have .doc and .xls etc files in my directory it creates 2 groups and add files according to groups

• Create a windows application
• Drag and drop ListView Control on to the form
• Drag and drop FolderBrowseDialog on to the components panel
• Drag and drop a Button on to the form
• Double click on the button and add following code

private void button1_Click(object sender, EventArgs e)
{
//Opens a folder browser dialog box for selecting the directory
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
//Clear the items before adding new items
listView1.Groups.Clear();
listView1.Items.Clear();
//Get all files from selected directory
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//loop through all the files to add to list view
foreach (string file in files)
{
listView1.ShowGroups = true;
//get file extention
string strExtn = Path.GetExtension(file);
//Check whether group is already added or not
ListViewGroup lstGroup = listView1.Groups[strExtn];
if(lstGroup == null)
{
//if not added add the new group with file type
lstGroup = new ListViewGroup(strExtn, strExtn);
listView1.Groups.Add(lstGroup);
}
//finally add list item to listview
ListViewItem lstItem = new
ListViewItem(Path.GetFileName(file), lstGroup);
listView1.Items.Add(lstItem);
}
}

Labels:

Sample Code - Regular Expression

This code shows how to use regular expression in c#

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

namespace RegularExpression
{
class Program
{
static void Main(string[] args)
{
Validation valid = new Validation();
bool flag = valid.IsAlphaNumeric("10A");
Console.WriteLine(flag);
}
}
//Class for the Validation
class Validation
{
//Function to test for the positive integer
public bool IsNaturalNumber(string strNumber)
{
Regex NotNatural = new Regex("[^0-9]");
Regex Natural = new Regex("0*[1-9][0-9]*");
return !NotNatural.IsMatch(strNumber) && Natural.IsMatch(strNumber);
}
//Function for test the natural numbes with zero
public bool IsWholeNumber(string strNumber)
{
Regex whole = new Regex("[^0-9]");
return !whole.IsMatch(strNumber);
}
//Function to check for a given string is a number or not
public bool IsNumber(string strNumber)
{
Regex NotNumberPattern = new Regex("[^0-9]");
Regex TwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex TwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
string strValidRealPattern = "^([-][.][-.]|[0-9])[0-9]*[.]*[0-9]+$";
string validIntegerPattern = "^([-][0-9])[0-9]*$";
Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + validIntegerPattern + ")");
return !objNumberPattern.IsMatch(strNumber) &&
!TwoDotPattern.IsMatch(strNumber) &&
!TwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);

}
//Function to check for the alphabets
public bool IsAlpha(string strCheck)
{
Regex objAlphaPattern = new Regex("[^a-zA-Z]");
return !objAlphaPattern.IsMatch(strCheck);
}
//Function to check for the alphanumeric
public bool IsAlphaNumeric(string strCheck)
{
Regex objAlphaNumeric = new Regex("[^a-zA-Z0-9]");
return !objAlphaNumeric.IsMatch(strCheck);
}
}
}

Labels:

ASP.NET Validation Controls with SampleCode

1.RequiredFieldValidator - is using for checking empty data or checking an initial value.


ErrorMessage="Enter Password" ControlToValidate="txtPassword"
SetFocusOnError="True">?



2.RegularExpressionValidator - is using for checking the data based upon a regular expression.


ErrorMessage="Invalid mail address" ControlToValidate="txtMail"
SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">?



3.RangeValidator - is using for checking whether the input is in a range as we specified.



ErrorMessage="Invalid data" ControlToValidate="txtPassword"
MaximumValue="100" MinimumValue="0" SetFocusOnError="True" Type="Double">?



4.CompareValidator - is using for comparing two controls.


ErrorMessage="Retype password" ControlToCompare="txtPassword"
ControlToValidate="txtRePassword">?

Labels:

Validation Controls in ASP.NET

Introduction

ASP.NET 2.0 offers a wide variety of ways to capture user input. This translates to, many opportunities for users to provide bad data. In this article, you will learn about the support that ASP.NET provides to you for performing data validation.

Validating Data

Often, bad data doesn't affect your organization until someone tries to report against it or some business intelligence project uncovers the presence of inconsistencies. If bad data is discovered in these circumstances, correcting it is an overwhelming, if not impossible, task. There could be millions of records with inconsistent and erroneous information. All these instances will skew your reports and make your business intelligence efforts more ambiguous.

So that you can avoid correcting bad data, you must validate data at the time of entry and, thereby, prevent bad data from getting into your systems. ASP.NET 2.0 provides some excellent support for performing data validation. In this article, you will see, choosing an appropriate data validation technique and then how to implement that technique using the intrinsic ASP.NET 2.0 data validation controls.

Appropriate Data Validation Technique

In a multi-tier architecture, the input source is not restricted to the UI and presentation layers. Data can come from many different sources such as other internal systems, other external systems, and other components of the same system. In this situation, it is not sufficient to rely solely on the presentation layer for validation.

On the other hand, if your application receives its input exclusively from the UI, then you can rely solely on the UI to validate the input data. In this article, we will mainly focus on validating data provided via a Web-based UI.

Validation Controls Common Properties

It should be no surprise that ASP.NET provides a solid base of validation controls. You can use these flexible controls out of the box or build on them through inheritance to create your own validation controls.

All ASP.NET validation controls have some common properties with which you should be familiar. The following listing describes the common properties among validation controls.


ControlToValidate: This property is used to indicate which control the validation control is to validate.

Display: This property provides three possible values. Setting the property to None prevents the control from being displayed inline. Use this setting in conjunction with the ValidationSummary control. The Static setting renders the validation control inline with other controls. This means that blank space is occupied by the control when it is not showing a message. Use the Dynamic setting when you want to avoid the control occupying blank space.

EnableClientScript: Not every browser supports JavaScript, and even browsers supporting it might have it disabled. However, for those browsers that support JavaScript, the validation controls can perform client-side validation as well as server-side validation. Client-side validation does not require a postback for validation to occur, resulting in a richer user experience. Note that client-side validation should be used only to provide a richer user experience and not as a replacement for server-side validation.

Enabled: This property determines whether the validation control actually performs validation.

ErrorMessage: This property is generally associated with the ValidationSummary control.

ForeColor: Use this property to set the color of the inline error message when validation fails.

IsValid: This property is used to evaluate whether validation fails.

SetFocusOnError: Setting this property to True causes the focus to be set to the control identified in the ControlToValidate property if validation fails.

Text: The Enabled property determines whether the validation control actually performs validation. The Text property is generally associated with the inline message–the message displayed at the location of the validation control.

ValidationGroup: Validation groups are new to .NET 2.0. This property is used to associate the current validation control with a specific validation group.

Now that you have been introduced to the common attributes of validation controls, you can dig deeper into specific facets of each validation control. You can use validation controls in combination. For example, you can use RequiredFieldValidator and RegularExpressionValidator controls on the TextBox control for capturing an e-mail address.

Labels:

N-Tier Architecture in Asp.net

Introduction


When Developing an Application various issues have to taken while designing the architecture of the application such as Performance, Scalability, Enhancements of the application, Security. So while deciding the architecture for an application we have to keep all the said issues in mind. That is the importance we need to give for the Architecture of an Application.

Firstly what is n-Tier architecture? It refers to the architecture of an application that has at least 3 "logical" layers or parts that are separate. Each layer interacts with only the layer directly below, and has specific function that it is responsible for.

The main advantage of n-Tier architecture is each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.
The another advantage of this architecture is if we change or add a layer, it can be done without redeploying the whole application For example, by separating data access code from the business logic code, when the database servers change you only needs to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.

Generally n – Tier Application has 3 layers they are

1. Presentation Layer
2. Business Layer
3. Data Access Layer


1 . Presentation Layer


Presentation Layer is nothing but a piece of software that deals with User interface of the Application. Displaying Data to the user and allowing him to interface with it is the main functionality. "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

We can create Presentation layer by Windows Forms or Asp.net Web Forms
Windows Forms are basically used to create traditional Desktop application.
They can offer rich UI design. The main drew back of windows application is they need to install on each and every machine.

On the other hand ASP.net web forms also offer rich UI. They are mainly used for web applications.

2 . Business Logic Layer


Business Logic Layer is responsible for processing the data retrieved and sent to the presentation layer. The main task of Business layer is business validation and business workflow

In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.

.Net Components forms these layers. Asp.net web service can also serve as Business Logic Layer. But they should be use only if the business validation happens at some external place other than our network.

By using .Net Remoting we can distribute the logic to other machines also.


3 . Data Access Layers


Data Access Layer deals with data manipulation actions such as Insert, edit, delete, select

in .NET Database can be from SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML.You should design data access layer in such a way that other layers need not have any knowledge about underlying data store.

ADO.NET is the data access technology under .NET. Though ADO.NET allows connected data access via DataReader classes more focus is on disconnected data access. DataSet plays a key in this mode. In some rare cases you can also use ADO for data access but it's use should have valid reasons. Do not use ADO just because you like Recordset!

Again .NET components form this layer. As stated earlier you may also use classic COM components.

Web services can also form data access layer. This is especially true if your database do not have a data provider. In such cases you can write some custom code to connect with the data and populate DataSet with it and then return DataSet to the caller.

In addition to ADO.NET you can also make use of built-in RDBMS capabilities such as stored procedures and functions


Passing data from one layer to another


Passing data from one layer to another is required in almost all the cases. Traditionally developers used comma separated strings, arrays and disconnected recordsets to achieve this. In .NET, DataSet provides an excellent way to pass your data across layers. You can even create the DataSet programmatically and populate it with your data. If you like objects a lot then you can make use of "Typed DataSets". Typed DataSet is nothing but a class derived from DataSet that exposes the tables and rows as objects.


Advantages


1. Reduces tight coupling between User interface, business process and database.
2. change in database or any data access methods do not have effect on the presentation layer.
3. It becomes easier to modify or extend your application, without breaking or recompiling the client-side code

Labels:

Serialization -XML serialization and Binary serialization

What is serialization?

Serialization is the process of saving the current state of any object into persistent storage (like file system), so that it can be retrieved later (Deserialize) and re create the same object.

For example, you have an object called student. You assign some values into the properties of this student object and serialze this object into a file. You can keep this file and de serialize any time later to re produce your student to the saved state.

What is serializable class ?

If a class can be serialized by using the builtin serialization features in .NET, that class is called serializable class. Most of the classes provided by .NET Framework is serializable.

Different types of Serialization

There are two broad categories of serialization in .NET

1. XML Serialization
2. Binary Serialization

XML Serialization serializes the object into an xml file. This file is human readable and can be shared with other applications.

Binary serialization is more efficient, but the serialized file is in binary format. It may not make any sense for a human being to open this file and understand what it contains. It is a stream of bytes.

Can I make my own classes serializable ?

Yes, it is very easy to make any class serializable. Simply add an attribute called 'Serializable' just above the class declaration and your class is serializable - means anybody can write few lines of C# code to save the state of the instance of your class into disk and retrieve (deserialize) later.

[Serializable]
public class MyClass
{
public string name;
public string adress;
}

How to serialize classes ?

The following samples demonstrate how to do XML Serialization and Binary Serialization using .NET classes.

We are serializing an 'ArrayList' object into disk and deserializing it again from the disk into another array list.

If you are not familiar with ArrayList - it is a collection class provided by .NET Framework, which can hold a list of any objects. The sample shown below uses an ArrayList which holds a list of strings.

XML Serialization

ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );

XmlSerializer serializer = new XmlSerializer( typeof(ArrayList) );

TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();

In the first step, we are creating an array list and adding two strings into it. next step is to create an instance of XmlSerializer class, which is provided by .NET Framework to help serialize any objects. In the constructor of XmlSerializer class, we have to specify what type of object we want to serialize using this. Since we are going to serialize an ArrayList, we are specifying 'typeof(ArrayList)'.

Next, we are going to do the real thing - saving the state of the ArrayList into an XML file. We will create a TextWriter object and specify the xml file name to which we will save the ArrayList.

The following lines will save the arraylist 'itemsToSerialize' into the file 'MyApplicationData.xml':

TextWriter writer = new StreamWriter( @"MyApplicationData.xml" );
serializer.Serialize( writer, itemsToSerialize );
writer.Close();

Now, you can check the folder where your application executable is. A file with the name 'MyApplicationData.xml' will be created and you can open the file in any text editor to see the content.

Deserialization

We have serialized an arraylist into an xml file. This means, the state of the arraylist is saved into the xml file. So, we should be able to retrieve the same arraylist from this xml file. The following code will deserialize the arraylist from the xml file.

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );

stream.Close();

Just few lines of code ! The above code will read the XML file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized' - means the list of items we originally saved into the XML file will be loaded back to the array list. Now the arraylist 'itemsDeserialized' will contain two strings 'john' 7 'smith' whcih we saved as part of the serialization process.

Binary Serialization

Binary serialization is pretty much same as XML serialization, except that the data stored in a stream of bytes, not in XML format. See the sample code :

ArrayList itemsToSerialize = new ArrayList();
itemsToSerialize.Add ( "john" );
itemsToSerialize.Add ( "smith" );

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Create );
IFormatter formatter = new BinaryFormatter();
formatter.Serialize( stream, itemsToSerialize );

stream.Close();

The above code sample will serialize the arraylist 'itemsToSerialize' into the file 'MyApplicationData.dat'.

Deserializing the binary data

The objects serialized using binary formatter can be deserialized the same way.

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();
ArrayList itemsDeserialized = (ArrayList)formatter.Deserialize( stream );

stream.Close();

The above sample will read the file 'MyApplicationData.dat' and restore the arraylist 'itemsDeserialized'.

Where is Serialization used

Serialization has lot of uses in application development. One important purpose is to transmit data between application domains. Webservices and remoting uses serialization/deserialization technique to exchange data.

When you call a webservice and pass parameters, the parameters are serialized into XML data and send to the server. When the webservice return data, the result is serialized into XML and returned to the caller. This means, you can pass only serializable data in web service calls.

In Remoting, you can choose either Binary or SOAP(XML) formatting. Depending on what format you choose, data is serialized using xml or binary format and exchanged between the server and client.

In addition to the above, you can use serialization as a way to store the application data into files. For example, you want to save the last logged in user name, but you don't have a database. You can serialize the user object itself or serialize just the name of the user into disk. When you start the application next time, you can deserialize the user name from the serialized data. Many of the applications use this serialization mechanism to remember the user settings and application data.

Summary

The classes provided by .NET Framework make it very easy to persist the state of any serializable object and restore it to the same state. In the above samples, we have used an ArrayList object. Instead of ArrayList, we can serialize/de serialize any serializable objects including custom classes.

Labels:

User Controls Sample Code

Introduction:

The User control is a Web based control, introduced by .net. Using this we can easily create your own custom, reusable controls. The user controls are compiled, when first requested and stored in server memory to reduce the response time for subsequent requests.

To create a user control, create a new file and give it a name with the extension .ascx.

Sample Code



< %@ Register TagPrefix="Acme" TagName="Login"
Src="Loginmenu.ascx" %>

< html>

< script language="VB" runat="server">

Sub Page_Load(Sender As Object, E As EventArgs)

If (Page.IsPostBack)
lbl1.Text &= "UserId" & Login.UserId & "< br>"
lbl1.Text &= "Password" & Login.Password & "< br>"
End If
End Sub

< /script>
< body>
< h3>User Control for Loginpage< /h3>
< form runat="server">
< Acme:Login id="Login" UserId="Test Spider" Password="test"
BackColor="beige" runat="server"/>
< /form>
< asp:Label id="lbl1" runat="server"/>

< /body>
< /html>


Calling User control from .aspx page


< %@ Page Language="vb" Codebehind="Callingusercontrol.aspx.vb"
Inherits="WebApplication.Callingusercontrol" %>

< %@ Register tagname="menu" tagprefix="uctrl" src ="Loginmenu.ascx" %>

Labels:

LINQ Query

Introduction:

LINQ - Language Integreted Query is repeadily used in these days. The presented article is elaborate the idea "How to describe a LINQ Query".

Simply, a query is an expression that retrieves data from a data source.

Scope:

The scope of the presented article is upto its title and projected scenarios.
Basics
LINQ Actions
Some basic example
Creating a LINQ project using Visual Studio


Description:

Now lets elaborate the topic in following points:

1. Operation of LINQ Query:

LINQ query consists three distinct actions as defined bellow:

(a) In this step LINQ gather the DataSource it may be any source of data.
(b) In next step have to create the Query
(c) Finally, execute the Query.

Lest, go through the following code-lines and try to understand the above operations:


class LINQQuery
{
static void Main()
{

// This is the Data source - Operation - I
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// Query Creation - Operation - II
var numQuery =
from num in numbers
where (num % 2) == 0
select num;

// Query Execution - Operation - III
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}


Three actions of LINQ Query [adapted from MSDN - bb397906]
FPRIVATE "TYPE=PICT;ALT=LINQ"

2. Skip and Take:

Skip, SkipWhile, Take, and TakeWhile are used to partition collectionsinto two parts and then return one of the parts. These partition features are only implemented as extension methods.

skip jumps to the indicated argument position in the sequence and returns everything after that.

SkipWhile accepts a predicate and instead of using a position, it
skips until the predicate evaluates to false.

Take grabs all of the elements up to the specified position in the index.

TakeWhile grabs all of the items in a sequence as long as the predicate evaluates to true.

3. Create a LINQ Project:

As per MSDN :

To use LINQ to XML or LINQ to DataSet in either C# or VB.Net language, you must manually add namespaces and references as described in the following :

If you are upgrading a project that you created by using an earlier version of Visual Studio, you may have to supply these or other LINQ -related references manually and also manually set the project to target .NET Framework version 3.5.

To target the .NET Framework version 3.5

In Visual Studio, open a Visual Basic or C# project that was created in Visual Studio 2005 and follow the prompts to convert it to a Visual Studio 2008 project.
For a C# project, click the Project menu, and then click Properties.
In the Application property page, select .NET Framework 3.5 in the Target Framework drop-down list.
For a Visual Basic project, click the Project menu, and then click Properties.
In the Compile property page, click Advanced Compile Options and then select .NET Framework 3.5 in the Target Framework (all configurations) drop-down list.


Important Points:
LINQ queries start with the keyword from.
In a LINQ query, you are always working with objects.
You an apply the basic operations to LINQ Query as follow:


Filtering is the common operation tyhrough which you can filter the data, consider following code:


//filter all employees on last name as 'Arora'
var lnqueryNames = from empname in employee
where empname.lastname == "Arora"
select empname;



Ordering sets the ordering for the output, lets take a loon in the following:


//display all Arora in ascending order with departments
var lnqueryNames = from empname in employee
where empname.lastname == "Arora"
orderby empname.dept ascending
select empname;



Ordering give the output in a group, consider following example:



var lnqueryNames = from empname in employee
group empname by empname.department;

foreach (var empbydept in lnqueryNames)
{
Console.WriteLine(empbydept.Key);
foreach (Employee emp in empbydept)
{
Console.WriteLine(" {0}", emp.lastName);
}
}

Labels:

Simple Web Services Application: Populating Grid view, Data Access.

Introduction:


The World Wide Web is more and more used for application to application communication. The programmatic interfaces made available are referred to as Web services. The label "web services," as broadly applied, has two levels of meaning — one is specific and another one is conceptual. .NET is the new distributed computing platform developed by Microsoft and ASP.NET is its programming model for web development. With the advent of .NET and the .NET Framework, Microsoft introduced a set of new technologies in the form of Web services and .NET remoting. ASP.NET Web services are powerful technologies that provide a suitable framework for developing distributed applications.

Overview of the Solution :


The main idea of this series of articles is not to make you feel as though you are learning a whole new technology altogether, but to realize that this new innovation is reusing existing knowledge to create a more capable and robust system in the Web World. Basically this article is article is to learn what a web service is? How to create a web service in .NET, How to access the database using web services? How to populate Grid View using web services?

Let’s see first what is a web service is. Web services are loosely coupled, reusable software components that semantically encapsulate discrete functionality and are distributed and programmatically accessible over standard Internet protocols.
Specifically, web services are a stack of emerging standards that describe service-oriented, component-based application architecture.

Conceptually, web services represent a model in which discrete tasks within e-business processes are distributed widely throughout a value net.

Standards :


Core Web service standards, includes
• Simple Object Access Protocol (SOAP),
• Web Services Description Language (WSDL), and
• Universal Description, Discovery and Integration (UDDI)

SOAP is based on XML and not a binary protocol, such as DCOM, you can inspect the data exchange in detail using a network tunneling tool and see exactly what is going on under the hood.

XML Web services are the fundamental building blocks in the move to distributed computing on the Internet. Open standards and the focus on communication and collaboration among people and applications have created an environment where XML Web services are becoming the platform for application integration.

WSDL (often pronounced whiz-dull) stands for Web Services Description Language. WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. WSDL is to SOAP what IDL is to CORBA or COM. Since WSDL is XML, it is readable and editable but in most cases, it is generated and consumed by software.

Controls used in this application

protected System.Web.UI.WebControls.GridView GridView1;

Namespaces used in this application:

• using System.Web.Services;
• using System.Web.Services.Protocols;
• using System.Runtime.InteropServices;
• using System.Configuration;
• using System.Diagnostics;
• using System.EnterpriseServices;
• using System.Xml;

Solution with Code :


Creating a web service using Visual Studio.NET is one of the easiest tasks. By using the visual studio.NET wizards you can create you web service in a minute. After creating your web service write a simple method for testing your web services. Here in this article I written a simple public method called DisplayTextMsg() this will written a string.

// Simple method :: This return a string
[WebMethod]
public string DisplayTextMsg()
{
return "My First Service For Testing";
}


Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service. The WebMethod attribute provides the following properties:

• BufferResponse - The BufferResponse property of the WebMethod attribute enables buffering of responses for an XML Web service method.
• CacheDuration - The CacheDuration property of the WebMethod attribute enables caching of the results for an XML Web service method.
• Description - The Description property of the WebMethod attribute supplies a description for an XML Web service method that will appear on the Service help page.
• EnableSession - The EnableSession property of the WebMethod attribute enables session state for an XML Web service method.
• MessageName - The MessageName property of the WebMethod attribute enables the XML Web service to uniquely identify overloaded methods using an alias.
• TransactionOption - The TransactionOption property of the WebMethod attribute enables the XML Web service method to participate as the root object of a transaction.

Database Access Method:


Now let’s write a simple method to connect to the database and fetch the data and return it as a XML document. Here in this article I have written that method as like this as follows.


// Simple method to access database :: This return a xml Document
[WebMethod]
public XmlDocument GetDataFromDB()
{
string errorMessage = "";
XmlDocument myDatas = new XmlDocument();
//Connection string is stored in the web.config file as an appSetting
string connectionString = ConfigurationSettings.AppSettings["DatabaseConnectionString"];
SqlConnection dbConnection = null;
// Open a connection to the database
try
{
dbConnection = new SqlConnection(connectionString);
dbConnection.Open();
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
if (errorMessage == "")
{
// Build an insert command
string SQL = "select * From ProfileContact";
SqlCommand GetCustomerCmd = new SqlCommand(SQL, dbConnection);

try
{
SqlDataAdapter custDA = new SqlDataAdapter();
custDA.SelectCommand = GetCustomerCmd;
DataSet custDS = new DataSet();
custDA.Fill(custDS, "ProfileContact");
myDatas.LoadXml(custDS.GetXml());
dbConnection.Close();

}
catch (System.Exception ex)
{
errorMessage = ex.Message;

}
finally
{
dbConnection.Dispose();
}
}
return myDatas;
}


After writing these methods lets see how we can access this web services in your ASP.NET web application. So first create a new web application. In the solution explorer window right-click on References and select Add Web Reference. In the Add a Web Reference window enter the path to your Web Service (http://localhost:2034/WebServices/Service.asmx ) Then Click on the Add Reference button. Here let’s see how the WebMethod are called in your ASP.NET WebPages. First initialize the web service in your class.
localhost.Service myService1 = new localhost.Service();
After initializing your web service, you can invoke WebMethod from that web services in your ASP.NET pages. First let’s see how the DisplayTextMsg() is invoked in your ASP.NET page. In this article I called this WebMethod in a button click event.


// Button Click Event
protected void Button1_Click(object sender, EventArgs e)
{
string serMsg = myService1.DisplayTextMsg();
lbl_display.Text = serMsg.ToString();
}



The above snippet is a simple demonsration.
Let’s see how a gridview control is populated using a web services and in this demonstration the web services will access the database and then it will populate the gridview. The WebMethod GetDataFromDB() will return a XML Document, I inserted that XML document into a Dataset and then the resulting Dataset is populated in the GridView.


// Data Binding :: DataSet Appending
public void DataBindFrmWS()
{
XmlDocument myServiceDoc = new XmlDocument();
System.Xml.XmlNode neNode;
//Adding the resulting XML from WebMethod to a user created XmlNode
neNode = myService1.GetDataFromDB();
//Creating a Dataset
DataSet myDataSet = new DataSet();
//The XmlNode is added to a byte[]
byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(neNode.OuterXml);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buf);
//The XML is readed from the MemoryStream
myDataSet.ReadXml(ms);

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


The above code snippets will populate your gridview control using data’s from Web Services. And now you can build your own web services and use it in any application you want. Now a small reference diagram how web services works, the architectural diagram.

Labels:

Smart Clients Applications : ClickOnce Deployement Features of VS.NET 2005

What is a Smart Client Application?


Smart client applications can be designed to combine the benefits of a rich client
Application with the deployment and manageability strengths of a thin client
Application, although the precise nature of the balance between the two approaches
Depends on the exact scenario.

Smart client applications often have very diverse requirements, and so vary greatly
In design and implementation. However, all smart clients share some or all of the
Following characteristics:

• Make Use of Local Resources
• Make Use of network Resources
• Support occasionally connected users
• Make use of network resources
• Support, Provide intelligent installation and update
• Provide client device flexibility




What is ClickOnce Feature of .NET 2005?


ClickOnce is a deployment technology that enables self-updating Windows-based applications that can be installed and run with minimal user interaction. Applications are published to a file share, Web Site, or media such as a CD.
Once published, ClickOnce apps can be automatically updated with minimal user input.
ClickOnce deployment overcomes three major issues inherent in deployment:
• Difficulties in updating applications. With Microsoft Windows Installer deployment, whenever an application is updated, the user must reinstall the entire application; with ClickOnce deployment, you can provide updates automatically. Only those portions of the application that have changed are downloaded, then the full, updated application is reinstalled from a new side-by-side folder.
• Impact to the user's computer. With Windows Installer deployment, applications often rely on shared components, with the potential for versioning conflicts; with ClickOnce deployment, each application is self-contained and cannot interfere with other applications.
• Security permissions. Windows Installer deployment requires administrative permissions and allows only limited user installation; ClickOnce deployment allows non-administrative users to install and grants only those Code Access Security permissions necessary for the application.




The core ClickOnce deployment architecture is based on two XML manifest files: an Application manifest file and a Deployment manifest file.

The application manifest describes the application itself, including the assemblies, the dependencies and files that make up the application, the required permissions, and the location where updates will be available. The application developer authors the application manifest by using the Publish Wizard in Visual Studio 2005 or the manifest generation tool (Mage.exe) in the .NET Framework SDK.

The deployment manifest describes how the application is deployed, including the location of the application manifest, and the version of the application that clients should run. An administrator authors the deployment manifest using the manifest generation tool (Mage.exe) in the .NET Framework SDK.
To make a ClickOnce application available to users, you must publish it to a Web server; file share, or removable media. You can publish the application using the Publish Wizard; additional properties related to publishing are available on the Publish page of the Project Designer or you can publish the application on the server manually.


To Publish to Web Using Publish Wizard


1. In Solution Explorer, select the application project.
2. Right-click the project node and choose Publish. The Publish Wizard appears.
3. On the Where do you want to publish the application? Page; enter a valid URL using the format http://localhost/foldername, then clicks Next.
4. In the “Will the application be available offline?” page, click the appropriate option:
o If you want to enable the application to be run when the user is disconnected from the network, click Yes, this application will be available online or offline. A shortcut on the Start menu will be created for the application.
o If you want to run the application directly from the publish location, click No, this application is only available online. A shortcut on the Start menu will not be created.
Click Finish to publish the application. Publishing status is displayed in the status notification area of the taskbar.

The above solution to deploy the ClickOnce applications is suitable for the Projects Where all the projects are under the same Project/Solution. It is not suitable for the projects in which all projects are separately built. Like in Our project there is a main logon application through which an user is login & then he/she will click on the applications available to that user and that application is executed. In this case we have to mention the start up exe file and dependent files in manifest files used for ClickOnce.The other way to publish your application on the Web Server is to manually create your application & deployment manifest file using a command line toll mage.exe provided by the .NET SDK.






To Publish the application manually on Web Server


To publish your application on the Web Server without using the publish wizard is little bit tricky. For this you have to follow the steps given below:

STEPS:
1. Please create one folder under wwwroot folder for example YourClickOnceApplication.
2. Create one subfolder under YourClickOnceApplication for example YourClickOnceApplication _1_0_0_0 since first time you are publishing application.
3. Copy your .exe, .dlls, resource files\folders & config files from bin\Release folder into YourClickOnceApplication _1_0_0_0.
4.Go to Start-->Program-->Microsoft .Net Framework SDK v2.0-->SDK Command Prompt & type MageUi.exe one window will open,

Mageui Screen.


5. Create a new application manifest by selecting File, New, Application Manifest from the menu.
6. On the default Name tab, enter the name and version number of this deployment.
7. Select the Files tab and click the Browse... button next to the Application Directory text box.
8. Select the directory containing your application files that you created in step 2, and click OK on the folder selection dialog box.
9. Click the Populate button to add all your application files to the file list. If your application contains more than one executable file, mark the main executable file for this deployment as the startup application by selecting Entry Point from the File Type drop-down list. (If your application only contains one executable file, MageUI.exe will mark it automatically for you.). To have a custom icon displayed in your ClickOnce application the icon must be deployed with the application and the file must be specified as the value for the iconFile attribute in the .exe.manifest file.
10. Select the Permissions Required tab and select the level of trust you need your application to assert. The default is Full Trust, which will be suitable for most applications.
11. Select File, Save from the menu, and save the application manifest. You will be prompted to sign the application manifest when you save it. Save it in folder created in step 2 (i.e. under YourClickOnceApplication _1_0_0_0 folder).
12. Select File, New, Deployment Manifest from the menu to create your deployment manifest, and then on the Name tab, supply a name and version number (1.0.0.0 in this example).
13. Select the Publisher tab, and supply values for Publisher and Product. (Product is the name given your application on the Windows Start menu when you install your application locally.)
14. Switch to the Deployment tab, Select the Application type as Install locally & give the URL of the virtual directory which u have created in step1 named YourClickOnceApplication like here you can give like http://localhost/ YourClickOnceApplication/YourAppName.application.
15. Switch to the Update tab, and specify how often you would like this application to update. If your application uses the ClickOnce Deployment API to check for updates itself, clear the check box labeled this application should check for updates if not check the checkbox Also you can define the way your application will self update.
16. Switch to the Application Reference tab. You can pre-populate all of the values on this tab by clicking the Select Manifest button and selecting the application manifest you created in 9th step.
17. Choose Save and save the deployment manifest to disk. You will be prompted to sign the application manifest when you save it. Save deployment manifest in folder created in step 1 (i.e. under YourClickOnceApplication folder).
That’s it now browse .application file from location given in step 12 for example
http://localhost/ YourClickOnceApplication/YourAppName.application
Note: ClickOnce doesn’t support Fire Fox browser. To Support fire fox you have to install a plug-in provide on URL.


Applications distributed with ClickOnce do not get installed in the program Files folder. Instead they are placed in an Application cache that resides in the Local Settings folder under the current user’s Document’s & Settings Folder. By controlling this aspect of the deployment, multiple versions of an application can reside on the client pc at the same time.
All ClickOnce applications, whether they are installed locally or hosted online, are stored on the client computer in a ClickOnce application cache. A ClickOnce cache is a family of hidden directories under the Local Settings directory of the current user's Documents and Settings folder. This cache holds all the application's files, including the assemblies, configuration files, application and user settings, and data directory. The cache is also responsible for migrating the application's data directory to the latest version. Because of this it is very simple process to rollback a ClickOnce application to its previous version. If the user goes to the Add/Remove programs control applet, the dialog presented will have the choice of removing the ClickOnce application or the rolling back to the previous version. An administrator can change the manifest file to point to the previous version.
By default, client computers have 250 MB of storage for online ClickOnce applications. Data files do not count toward this limit. A system administrator can enlarge or reduce this quota on a particular client computer by changing the registry key, HKEY_CURRENT_USER\Software\Classes\Software\Microsoft\Windows\CurrentVersion\Deployment\OnlineAppQuotaInKB, which is a DWORD value that expresses the cache size in kilobytes. For example, in order to reduce the cache size to 50 MB, you would change this value to 51200.
When you need to deploy a new version of the application, you will need to create a new directory named after the new version—for example, YourClickOnceApplication _1_1_0_0 and move the new application files into that new directory. You should generate a new application manifest and store it in the new directory, and have the publisher sign the new manifest. Once you get the signed manifest back, you can use Mage.exe to update the deployment manifest and point it at the new application manifest:
mage -Update YourAppName.application -Version 1.1.0.0 -AppManifest YourClickOnceApplication _1_1_0_0\ YourAppName.exe.manifest
Now when you will run your application it will ask that a new version is updated on server whether you want to install or not. If you say yes then it will download the entire latest file from the server and reinstall the application on your system.

Now there are some issues with this manual deployment of ClickOnce application in comparison to deployment through wizard. Like
• When you deploy through wizard it creates an html page by itself to show the application manifest URL and user can easily navigate through this URL to install the ClickOnce application.
• Other thing is if you want to add some prerequisites with your ClickOnce application through wizard it is very easy task you have to just Click On prerequisites button and it will provide you to add the prerequisites list. Wizard automatically creates a ‘SetUp.exe’ which contain that prerequisite installation URL and settings related to those prerequisites.
• Next thing is wizard automatically create a certificate (myapplication.pfx) to sign your application & deployment manifest files.
• If you want to change anything in application or deployment manifest files then you have to again sign it with the certificate (licence) provided by the issuer.



We can do the above task manually in following ways when we are deploying the ClickOnce application manually as:

We can use windows built in facility to create the certificate files. Using makecert command we can create a certificate (.pfx) and after creating this file we can add this certificate in Clients certificates. The level of trust that is being requested is part of trust license configuration. A public key is used to sign the application must also be supplied to the license issuer. The trust licence is then embedded in the deployment manifest. The last step is to sign the deployment manifest with your own key pair. To Sign the application and deployment manifest we can use following commands as:

mage -s app manifest -cf cert_file -pwd password
mage -u deployment manifest -appm app manifest
mage -s deployment manifest -cf certfile -pwd password

To add the prerequisite for ClickOnce Deployment This should be added in application.exe.manifest file (Application Manifest file) for .NET 2.0 framework

Labels:

Overview of .net Remoting

Introduction:

” Remoting system is an architecture designed to simplify communication between Objects running in different Application Domains, whether they're on the same computer”.

Prior to .Net Remoting, DCOM was the most used method of developing distributed application on Microsoft platform. Because of object oriented architecture, .NET Remoting replaces DCOM as .Net framework replaces COM.

Benefits of Distributed Application Development:

Fault Tolerance: Fault tolerance means that a system should be resilient when failures within the system occur.

Scalability: Scalability is the ability of a system to handle increased load with only an incremental change in performance.
Administration: Managing the system from one place.

In brief, .NET Remoting is an architecture which enables communication between different application domains or processes using different transportation protocols, serialization formats, object lifetime schemes, and modes of object creation. Remote means any object which executes outside the application domain. The two processes can exist on the same computer or on two computers connected by a LAN or the Internet. This is called marshalling (This is the process of passing parameters from one context to another.), and there are two basic ways to marshal an object:

Marshal by value: the Server creates a copy of the object passes the copy to the client.

Marshal by reference: the Client creates a proxy for the object and then uses the proxy to access the object.

Remoting Overview

Remoting in Asp.net is Distributed Programming model which is based on distributed objects; it is designed to provide the concepts of distributed component services as other technologies like DCOM provide but with out complexity . Unlike other similar technologies, which are essentially add –in tool kits that allow you to distribute objects among systems.

Remoting is an integral part of the .net framework because support for Remoting is built into the Framework, Remote objects support full .NET type system fidelity, including complex data types, support for inheritance, and objects passed by reference as well as by value

As said earlier the .Net Remoting Programming model is much simpler than earlier distribution models, the reason is it is an integral part of the .Net Frame work. In .Net Remoting, once you've established the Distributed Object Connection, you create and access distributed objects in exactly the same manner as you would create and access a local object. All of the details—Instantiating the server-based object, Lifecycle Management, Serialization, Marshaling Data, etc. are handled by the Framework without your intervention. Although there are issues that you have to keep in mind when working with Distributed Objects, the amount of extra work involved in setting up and managing Distributed Objects is very small.

NET Remoting is very flexible. You have a wide range of communications options and activation methods, as well as full control over a distributed object's lifecycle. You can choose TCP or HTTP communications protocols on any port, using text or binary formatting. The .NET Remoting infrastructure supports Server Activated Objects single call object and singleton object And Client Activated Objects. .NET Remoting gives you many opportunities to plug in to the system to customize Lifecycle Management, Marshaling, serialization, Messaging, and other services

The Remoting features that ship with the .NET Framework are built to provide distributed object services over the most common communications channels. However, if you have custom communications requirements, the pluggable architecture will allow you to create new protocols and use them with the Remoting system.
Security is important and necessary thing to any distributed application. Although the .NET Remoting infrastructure does not define any security features itself, because distributed applications are managed code they have full access to all of the .NET security features. In addition, the HTTP channel, when used with IIS, allows you to take full advantage of the authentication and authorization features that are available to Web based protocols. If you choose to use a protocol other than HTTP with IIS, then you have the opportunity to create your own security infrastructure.

Advantages and Disadvantages of Remoting


Coming To advantages of .Net Remoting

1. Remoting Supports Different type of Communication Protocols. It supports many protocols including SOAP, HTTP , this makes it better than Web services.

2. Remoting can share objects from any types of models.

3. Web services support only the data types defined in the XSD type system , therefore we can serialize only limited number of objects

4. Remoting is Highly Extensible to customize the different components of the .net Remoting frame work

Even though Remoting has advantages, it has its own Disadvantages too

1. The programming model is little bit difficult than web services.

2. Visual Studio .net Support for Remoting is not as wide as that of for web services.

3. Remoting Applications are Tightly Coupled.

4. Remoting Depends on assembly metadata to describe types, which means that any application that communicates with another, must have some intimate knowledge of the other's inner workings.

5. As it depends on assembly metadata, it implies that client applications must understand .NET concepts. Which, applications that make use of .NET Remoting are not interoperable with other systems.

Labels:

How to Creating Reports using ASP.NET Crystal Reports

Imports System
Imports System.Data
Imports System.Data.OleDb

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 ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\vb.net projects\dept_mstr.mdb"
Dim myConnection As OleDbConnection = New OleDbConnection
myConnection.ConnectionString = ConnString

Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim sql As String = "select distinct dept_no,dept_name from DEPARTMENT"
myConnection.Open()

Dim com As New OleDbCommand
Dim dbread
com = New OleDbCommand(sql, myConnection)
dbread = com.ExecuteReader
While dbread.read
DropDownList1.Items.Add(dbread.getVALUE(0))
DropDownList2.Items.Add(dbread.getstring(1))
End While

End Sub

Protected Sub CrystalReportViewer1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles CrystalReportViewer1.Init

End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Fltr
CrystalReportViewer1.ReportSource = "E:\WebSite2\crystalreport1.rpt"
Fltr = "{DEPARTMENT.dept_no}='" & Me.DropDownList1.Text & "' and '" & Me.DropDownList2.Text & "'"
CrystalReportViewer1.SelectionFormula = (Fltr)
End Sub
End Class

Labels: ,

How to Editing, Updating, Cancel, Selecting Rows in -Datagrid

Lets first set up our datagrid.
1. Drag and Drop the datagrid control from your toolbox to the webform.
2. The datagrid will appear as a simple table.
3. You can make the datagrid pretty by selecting the Auto format features.

Okay your datagrid is set up, lets add some columns. Adding the Bound Columns: Adding the bound colums in the datagrid is pretty simple.
1. Right click on the datagrid and select Property Builder.
2. Click on the Columns tab and uncheck "Generate columns automatically".
3. Add three bound columns, give the columns some name in the column name field. And finally add the edit,update,cancel buttons which can be found under the button option.

Storing the database connection

In this demo I am storing the database connection in the Web.config file. The database name is DBSnippets, which has one table known as tblPerson. Here is the web.config file.

WRITE ALL THIS CODE IN HTML TAGSconfiguration appSettingsadd Key="ConnectionString" value="server=localhost;database=DBSnippets"appSettingsconfiguration.

Okay till now we have made the Datagrid and also saved the connection string in the web.config file. Now the time has come to code and handle the events. Lets first make the BindData method which will retrieve the contents from the database and bind it on the screen. This will be one of the most important methods since it will be called whenever the page is loaded for the first time.

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindData();
}
}
As you see the BindData method is called when the page is not posted back.

Now lets see the BindData method in details.

public void BindData()
{
SqlCommand myCommand = new SqlCommand("SP_SELECT_PERSONS",myConnection); myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds,"tblPerson");
myConnection.Open();
myCommand.ExecuteNonQuery();
myDataGrid.DataSource = ds;
myDataGrid.DataBind();
myConnection.Close();
}

Explanation of the BindData method:

1. First we make a SqlCommand object and named it myCommand. The SqlCommand object takes a stored procedure as an input and the SqlConnection.
2. We feed the command object to the DataAdapter object named as myAdapter.
3. A dataset is declared which is filled with the result of the Stored procedure.
4. myDataGrid.DataBind() binds the datagrid to the page. Don't forget to bind the grid or else it won't be displayed.
5. Later we opened the connection and execute the query.

Now Lets see the stored procedure. Stored Procedure:

CREATE PROCEDURE SP_SELECT_PERSONS AS SELECT * FROM tblPerson
GO
As you can see that the above Stored Procedure is pretty simple. All we are doing is we are just selected all the columns from the table person. Lets now make the Edit method which will display textboxes inside the datagrid so that a user can insert data. This sort of editing is also known as Inline editing. Making datagrid editable is pretty simple. All you to do is to code few lines in the EditCommand event of the datagrid. You can view all the events supported by DataGrid by selecting properties and than selecting the Thunder/Flash yellow sign at the top of the properties window.
Lets call our Edit DataGrid event Edit_DataGrid.

private void Edit_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{ // We use CommandEventArgs e to get the row which is being clicked // This also changes the DataGrid labels into Textboxes so user can edit them myDataGrid.EditItemIndex = e.Item.ItemIndex; // Always bind the data so the datagrid can be displayed. BindData();
} As you see when you click the edit link the update and the cancel link button automatically appears. Lets now see the code for the Cancel Event. Cancel event is used when you are in the edit mode and you change your mind about not to edit. So you click the cancel link button and the Datagrid returns back to its orginal condition.

private void Cancel_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{ // All we do in the cancel method is to assign '-1' to the datagrid editItemIndex // Once the edititemindex is set to '-1' the datagrid returns back to its original condition myDataGrid.EditItemIndex = -1; BindData();
} Okay now we come to a slightly difficult step. We will carefully look at the Update method and see how it works.

private void Update_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
System.Web.UI.WebControls.TextBox cName = new System.Web.UI.WebControls.TextBox();
cName = (System.Web.UI.WebControls.TextBox) e.Item.Cells[1].Controls[0];
SqlCommand myCommand = new SqlCommand("SP_UpdatePerson",myConnection); myCommand.CommandType = CommandType.StoredProcedure; myCommand.Parameters.Add(new SqlParameter("@PersonName",SqlDbType.NVarChar,50));
myCommand.Parameters["@PersonName"].Value = cName.Text;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
myDataGrid.EditItemIndex = -1;
BindData();
}
Lets now dig into this method and see whats going on. • The name of the method as you can see is Update_DataGrid, this event is fired when you click the update link button which appears after clicking the edit button. • We declare a variable of TextBox type and call it cName. The reason of declaring a TextBox is that the value that we want is inside the TextBox which is inside the DataGrid control. • Later we made the SqlCommand object which takes stored procedure "SP_UpdatePerson", which will be discussed afterwords. • After marking the command object with the stored procedure we passed the parameter which is PersonName. • Finally we execute the Query and set the editItemIndex property of the DataGrid '-1' which will bring the datagrid back to its original form i.e without any textboxes. • Don't forget to bind the datagrid.

Update Stored Procedure:
CREATE PROCEDURE SP_UpdatePerson @PersonName nvarchar(50) AS UPDATE tblPerson SET PersonName = @PersonName WHERE PersonName = @PersonName; Selecting Item from the Datagrid: Another cool feature of the Datagrid control is that you can select any row from the datagrid and it will be displayed as the highligted row in the grid. The highlight row event is called SelectedIndexChanged event. The event is called when the select column is clicked. The select column can be added to the datagrid using the property builder, just like we added "edit/cancel/update" link buttons. // This event is fired when the Select is clicked private void Select_DataGrid(object sender, System.EventArgs e) { // prints the value of the first cell in the DataGrid Label2.Text += myDataGrid.SelectedItem.Cells[0].Text; }

Labels: