GridView in ASP.Net

GridView plays very important component in ASP.Net Application. It covers most of the basic reports for which you do not need any reporting component like Crystal Report, Report Viewer etc.

Major concern with any data entry form is Add, Edit, Delete and View.


Assumptions-

We are using SQL Server Express editions as Database.

Table Name- Employees

Fields- EmpId, EmpName, Designation

Take GridView control on page and set the ID property to dgEmployees.

Go to property builder by right click on GridView -> Show Smart Tag -> Edit Columns. Uncheck Auto-Generate Field from the Property window.

Add three TemplateField Column for Employee Name, Designation, & Delete Button. Add Edit button from CommandField Group from Property Window.

TemplateField Colums have ItemTemplate, Alternating Item Template, Edit Template, Header Template, Footer Template.

Each template columns Item Template field contains Label Control & Edit Template contains TextBox control for Editing item. Set the Binding Field name to the Text Property of both controls for each template field to the respective Database Column Name i.e Eval(“EmpName”).

Set the DataKeyNames property of GridView to Primary Key Column of DataBase i.e. EmpId. This property binds the database column field value to each row of gridview as a Unique Identifier.

Set the data bindings for Delete Button for CommandArgument Eval(“EmpId”); for saving the ID column value from database for fetching the ID field value while Deleting the Record. Set the CommandName property to Delete Button to CMDDelete. The CommandName property can contain any string name which can be used to recognize the type of command invoked from gridview. Because when any of the event generated in GridVeiw it fires RowCommand Event. In this event we have to handle the Delete Button Code. Instead if you are using default Delete Button of GridView then register for RowDeleting event of GridView and for accessing Unique ID columnvalue from database you need to fetch the id from DataKeys collection of GridView. For e.g.

int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);

Place the Textbox control in the grids Footer template for Adding new record. Set the CommandName to CMDAdd for Add button.

Register events for Edit, Update, Cancel button of gridview ??” RowEditing, RowUpdating, RowCancelEditing.

View in GridView

To view data in gridview is very simple. Just create a DataSet using SqlDataAdapter??Ts Fill method and set the GridViews DataSource Property to DataSet.

Create a Method to Bind the GridView to DataSource named BindGrid. This method fetches data from the GetEmployees method which returns DataSet from Employees table.

Call the BindGrid on Page_Load in !IsPostBack block to fill the grid by default.

private void BindGrid()

{

dgEmployees.DataSource = GetEmployees();

dgEmployees.DataBind();

}



private DataSet GetEmployees()

{

DataSet ds = new DataSet();

SqlConnection conn = new SqlConnection();

conn.ConnectionString =ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;

SqlDataAdapter da = new SqlDataAdapter("Select * From Employees", conn);

try

{

da.Fill(ds);

return ds;

}

catch { }

finally

{

conn.Close();

conn.Dispose();

}

return null;

}

Edit in GridView

For Editing Register RowEditing event of GridView. To switch the normal mode to Edit mode of gridview EditIndex property plays important role. EditIndex specifies which row is in edit mode by setting RowIndex to it. By default EditIndex of gridview is -1 (Normal mode). If you want to edit 3rd Row then set the EditIndex to 2 (Row index starts from 0,1,2..).

After setting editindex refresh the grid by calling BinGrid. GridViewEditEventArgs object knows the current row index so getting row index of the selected row in gridveiw is not big deal; just e.NewEditIndex (e object of GridViewEditEventArgs).

protected void dgEmployees_RowEditing(object sender, GridViewEditEventArgs e)

{

dgEmployees.EditIndex = e.NewEditIndex;

BindGrid();

}


Cancel in GridView


For Cancel just reset the GridView editindex to default i.e. -1 and refresh the grid.

protected void dgEmployees_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

dgEmployees.EditIndex = -1;

BindGrid();

}


Update in GridView

For Update register RowUpdating event of the gridview. Find the Unique id for updating the row from DataKeys collection of gridview.

int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);

Find the controls in the selected row by using FindControl method of gridviews rows collection and collect data from the text boxes.

TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl(“txtEmpName”) as TextBox;

TextBox txtdesign = dgEmployees.Rows[e.RowIndex].FindControl(“txtDesignation”) as TextBox;

Finally update the row and refresh the grid.

if(txtname!=null && txtdesign!=null)

UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());

dgEmployees.EditIndex = -1;

BindGrid();


Complete code-

protected void dgEmployees_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

int empId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);

//Find Text boxex

TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl("txtEmpName") as TextBox;

TextBoxtxtdesign=dgEmployees.Rows[e.RowIndex].FindControl("txtDesignation") as TextBox;

if(txtname!=null && txtdesign!=null)

UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());

dgEmployees.EditIndex = -1;

BindGrid();

}


Custom Delete in GridView

For Delete register RowCommand event of the gridview. Find the Unique id for deleting the row from DataKeys collection of gridview. Check for CommanName and invoke delete method for the selected row.

protected void dgEmployees_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName.Equals("CMDDelete"))

{

int EmpId = Convert.ToInt32(e.CommandArgument);

DeleteEmployee(EmpId);

//Refresh Grid

BindGrid();

}

}


Add in GridView

Adding from GridView is just some trick with Footer Template. I added textboxes and a add button in the footer row of the gridview. When u are in Normal mode it is visible else it is invisible to synchronize between edit and add.

Like Updating find the Textbox and pass the values to Addemployee method like

else if (e.CommandName.Equals("CMDAdd"))

{

TextBox txtname = dgEmployees.FooterRow.FindControl("txtEmpName") asTextBox;

TextBox txtdesign = dgEmployees.FooterRow.FindControl("txtDesignation") as TextBox;

if (txtname != null && txtdesign != null)

{

AddEmployee(txtname.Text.Trim(), txtdesign.Text.Trim());

BindGrid();

}

}

The Complete code for EditEmployee, AddEmployee, UpdateEmployee, DeleteEmployee is in Source File.

The code should be in RowCommand event only. Due to this we use CommandName for different button control to differentiate between the type of code to be handled by gridview.

ASP.Net Server Variables

Below is the detailed table for showing the ServerVariables Collection information.

Variable Name Description
ALL_HTTP HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:*/* HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:sv HTTP_HOST:localhost:1229 HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)
ALL_RAW Connection: Keep-Alive Accept: */* Accept-Encoding: gzip, deflate Accept-Language: sv Host: localhost:1229 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)
APPL_MD_PATH  
APPL_PHYSICAL_PATH D:\code\web\demos\membership\
AUTH_TYPE NTLM
AUTH_USER SYSTEMEN-D9AE02\Stefan Holmberg
AUTH_PASSWORD  
LOGON_USER SYSTEMEN-D9AE02\Stefan Holmberg
REMOTE_USER SYSTEMEN-D9AE02\Stefan Holmberg
CERT_COOKIE  
CERT_FLAGS  
CERT_ISSUER  
CERT_KEYSIZE  
CERT_SECRETKEYSIZE  
CERT_SERIALNUMBER  
CERT_SERVER_ISSUER  
CERT_SERVER_SUBJECT  
CERT_SUBJECT  
CONTENT_LENGTH 0
CONTENT_TYPE  
GATEWAY_INTERFACE  
HTTPS  
HTTPS_KEYSIZE  
HTTPS_SECRETKEYSIZE  
HTTPS_SERVER_ISSUER  
HTTPS_SERVER_SUBJECT  
INSTANCE_ID  
INSTANCE_META_PATH  
LOCAL_ADDR 127.0.0.1
PATH_INFO /membership/servervariables.aspx
PATH_TRANSLATED D:\code\web\demos\membership\servervariables.aspx
QUERY_STRING  
REMOTE_ADDR 127.0.0.1
REMOTE_HOST 127.0.0.1
REMOTE_PORT  
REQUEST_METHOD GET
SCRIPT_NAME /membership/servervariables.aspx
SERVER_NAME localhost
SERVER_PORT 1229
SERVER_PORT_SECURE 0
SERVER_PROTOCOL HTTP/1.1
SERVER_SOFTWARE  
URL /membership/servervariables.aspx
HTTP_CONNECTION Keep-Alive
HTTP_ACCEPT */*
HTTP_ACCEPT_ENCODING gzip, deflate
HTTP_ACCEPT_LANGUAGE sv
HTTP_HOST localhost:1229
HTTP_USER_AGENT Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)

Storing Objects into Permanant DataStore in ASP.Net

Hi All,

I was facing a problem towards sharing a data between Flash and .Net. The easiest way i found is XML Seralization because Remoting is much heavy and it requires remoting implementation. Even now I can store the Calss objects permanantely. This can be used in concept of Hibernate (Some what at very basic level).

I found XML Seralization because there must be some common bridge between two different technoloiges for communication. XML will act as common bridge between .Net and Flash.

XML Seralization can be done by System.Xml.Serialization.XmlSerializer class from System.Xml.Serialization namespace.

Assume our class defination looks like below –

namespace EShopping
{
public class Category
{
private int _CategoryId;
public string CatName;
public int CategoryId
{
get{return _CategoryId;}
set{_CategoryId=value;}
}
}
}

Our object has below contents-

EShopping.Category c = new EShopping.Category();
c.CategoryId = 1;
c.CatName = “Hello”;

Now we want to seralize this object to the XML by XML Seralization.

System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(EShopping.Category));

XmlSerializer Class has a method called Seralize and Deserialize.
Seralize method requires parameter Textwriter and class object to seralize.

System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(EShopping.Category));

System.IO.TextWriter tw = new System.IO.StreamWriter(Server.MapPath(“SeralizeClass.xml”));

ser.Serialize(tw, c);

tw.Close();

That’s it. Now you can see the SeralizeClass.xml file in your Web root directory. You can access this into any of the technologies which has xml support.

Accessing Seralize Object into .Net-

This is pretty straight forward and just access the object by Deserialize methotd of XmlSerializer Class.

System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(EShopping.Category));

System.IO.TextReader tr = new System.IO.StreamReader(Server.MapPath(“SeralizeClass.xml”));

EShopping.Category c = (EShopping.Category)ser.Deserialize(tr);

tr.Close();

Happy Coding 🙂