Showing posts with label Asp.Net - GridView. Show all posts
Showing posts with label Asp.Net - GridView. Show all posts

Wednesday, August 18, 2010

Perform Editing and Deleting with GridView Control

Editing and Deleting with GridView Control
Follow the following steps
  • First you place a GridView Control on the web form.
  • Under Add/Edit Column window, add apropriate columns ( I have added BoundColumns) to display data. Set its DataField property too.
  • Set AutoGenerateEditButton and AutoGenerateDeleteButton property into true.
  • Set GridView's apropriate events.
I have used Employee table to demonstrate this example. It has EmpId, Name, JobTitile and Salary columns.

public partial class GridViewAllCode : System.Web.UI.Page

{
SqlConnection con;
SqlCommand cmd;
DataTable dt;
SqlDataAdapter adp;


protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename="+Server.MapPath("App_Data")+"\\jobin.mdf"+";Integrated Security=True;User Instance=True");
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
if (!IsPostBack)
BindGrid();
}


private void BindGrid()
{
adp = new SqlDataAdapter("select * from Employee", con);
dt = new DataTable("Emp");
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}


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


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
string name=((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string jobTitle=((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
int salary = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
cmd.CommandText = "update Employee set Name='" + name + "', JobTitle='" + jobTitle + "', Salary=" + salary + " where EmpId=" + empId;
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
BindGrid();
}


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int empId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
cmd.CommandText = "delete Employee where EmpId=" + empId;
cmd.ExecuteNonQuery();
BindGrid();
}
}

Thursday, August 12, 2010

Reserved CommandName values

GridView Control's Reserved CommandName values and its Description

Cancel :  Cancels an edit operation and returns the GridView control to read-only mode. Raises the    RowCancelingEdit event.


Delete : Deletes the current record. Raises the RowDeleting and RowDeleted events

Edit : Puts the current record in edit mode. Raises the RowEditing event,

Page : Performs a paging operation. Sets the CommandArgument property of the button to "First", "Last", "Next", "Prev", or a page number to specify the type of paging operation to perform. Raises the PageIndexChanging and PageIndexChanged events

Select: Selects the current record. Raises the SelectedIndexChanging and SelectedIndexChanged events.

Sort: Sorts the GridView control. Raises the Sorting and Sorted events.

Update : Updates the current record in the data source. Raises the RowUpdating and RowUpdated events.

Custom Sorting with GridView Control | Handling GridView Sorting Event

Custom Sorting with GridView Control, Handling GridView Sorting Event

Bind a grid, and Set SortExpresion property for the particular field to be sortable (Eg, BoundField).
In the following example coulmn name is assigned to SortExpression property. I have a table with column with country; I need to sort records in ascending and descending order based on the country.

In the following example you can see three methods:

1. GridView1_Sorting :  GridView's Sorting event handling method.

2. Sort : implementation of sort logic

3. ManageViewState : To keep current sorting order.


#region Sort




protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
   Sort(e.SortExpression);
}


void Sort(string column)
{


switch(column)
{
case "Country":


if (ViewState[column] == null)
{
reportsSorted = (from r in report orderby r.Country ascending select r).ToList();
ManageViewState(column,true);
}

else
{
reportsSorted = (from r in report orderby r.Country descending select r).ToList();
ManageViewState(column, false);
}
break;


}


BindGrid(reportsSorted);
}



void ManageViewState(string key, bool Tokeep)
{
if (Tokeep)
    ViewState[key] = true;
else if(ViewState[key]!=null)
   ViewState.Remove(key);


}
#endregion


Have a look at above code and try to work out it.

Wednesday, August 11, 2010

Finding Row Index in GridView RowCommand Event

GridView RowCommand Event


The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs.

The GridView control also raises other specialized events when certain buttons are clicked; means buttons with the CommandName property set to "Delete", "Update", "Page" etc…

When using one of these buttons, you should consider handling one of the specialized events provided by the control; such as RowDeleted or RowDeleting.

We will discuss more about these specialized events later.

protected void gvProjects_RowCommand(object sender, GridViewCommandEventArgs e)
{


}

The above example shows a sample RowCommand event handling method.

A GridViewCommandEventArgs object is passed to the event-handling method, which allows you to determine the command name and command argument of the button clicked. To determine the command name and command argument, use the CommandName and CommandArgument properties, respectively. You can also access the button control that raised the event by using the CommandSource property.

To find index of row, which caused this event, we can use any of the following method:

1. We can use e.CommandArgument property to find row index. ( It will work only if we didn’t set the CommandArgument property of button which we clicked)

Eg:
int index = Convert.ToInt32(e.CommandArgument);

2. Second way is, we can find index from e.CommandSource property. See the following example to know more about it

Eg:
LinkButton lbtn = (LinkButton)e.CommandSource; // get event caused button
GridViewRow gvrow = (GridViewRow)lbtn.NamingContainer; // get grid row contains event caused button
int index = gvrow.RowIndex;


Hope It will help you to handle GridView's RowCommand Event.