Gridview Cool Tips & Tricks

Wednesday, August 27, 2008
Pop-up a Confirmation box before Deleting a row in GridView
Add a template field and drop a button in it, using which the user will delete the record. In the OnClientClick event, call the confirm() function as mentioned below:


CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete the record?');" />



Display details of the Row selected in the GridView
Assuming you have a button called ‘Select’ in your GridView with CommandName ‘Select’, to find out the row clicked and display the row’s details, use this code:
private void GridView1_RowCommand(Object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int idx = Convert.ToInt32(e.CommandArgument);
GridViewRow selrow = GridView1.Rows[idx];
string fstCell = selrow.Cells[0].Text;
string scndCell = selrow.Cells[1].Text;
// and so on
// Thanks to Mark Rae (MVP) for pointing the typo. Earlier it was Cells[1] and Cells [2]
}
}

Retrieve Details of the Row being Modified in GridView
void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
{
// Retrieve the row being edited.
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];

// Retrieve the value of the first cell
lblMsg.Text = "Updated record " + row.Cells[1].Text;
}

Retrieve Details of the Row being Deleted in GridView
The ID of the row being deleted must be in the GridView.DataKeyNames collection.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
// Query the database and get the values based on the ID
}
Cancelling Update and Delete in a GridView
RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control updates the row.
RowDeleting – Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.
protected void gvDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
e.Cancel = true;
}
void GridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
// Check for a condition and cancel the delete
// There should be atleast one row left in the GridView
if (GridView1.Rows.Count <= 1)
{
e.Cancel = true;
}
}

Enable Disable Controls inside a GridView
There are at times when you have to disable controls on some rows, when a certain condition is satisfied. In this snippet, we will see how to disable editing for rows that have the CategoryName as ‘Confections’. Use the following code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItem != null)
{
Label lblControl = (Label)e.Row.Cells[2].FindControl("lblCategoryName");

if(lblControl.Text == "Confections")
{
e.Row.Cells[0].Enabled = false;
}
}
}
}

How to Add a Row Number to the Gridview
There are a couple of ways to do this. However I will share a very handy tip that was shared by XIII in the
asp.net forums.
Just add the following tags to your section of your GridView <%# Container.DataItemIndex + 1 %>
How to programmatically hide a column in the GridView
There are two conditions to be checked in the Page_Load to hide a columns in the GridView, let us say the 3rd column:
If ‘AutoGenerateColumns’ = True on the GridView
C#
GridView1.HeaderRow.Cells[2].Visible = false;
foreach (GridViewRow gvr in GridView1.Rows)
{
gvr.Cells[2].Visible = false;
}
VB.NET
GridView1.HeaderRow.Cells(2).Visible = False
For Each gvr As GridViewRow In GridView1.Rows
gvr.Cells(2).Visible = False
Next gvr
If ‘AutoGenerateColumns’ = False on the GridView
C#
GridView1.Columns[2].Visible = false;
VB.NET
GridView1.Columns(2).Visible = False

Displaying Empty Data in a GridView
When there are no results returned from the GridView control’s data source, the short and simple way of displaying a message to the user, is to use the GridView’s EmptyDataText property.
DataSourceID="SqlDataSource1" EmptyDataText="No data available"
ShowFooter="true" AllowPaging="True" AllowSorting="True"
PageSize="5" OnRowDataBound="GridView1_RowDataBound">
Note: You can also add style to the EmptyDataText by using the
EmptyDataRowStyle property.
Displaying an Image in case of Empty Data in a GridView
As an alternative to using the EmptyDataText property, if you need to display an image or any HTML/ASP.NET control, you can use the EmptyDataTemplate. In this snippet below, we are using the image control in the to display an image.
DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True"
PageSize="5" OnRowDataBound="GridView1_RowDataBound">

ImageUrl="~/images/NoDataFound.jpg"
AlternateText="No data found"
runat="server"/>

Change the color of a GridView Row based on some condition
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
string catName = Convert.ToString(drv["CategoryName"]);
if (catName.Trim() == "Confections")
e.Row.BackColor = System.Drawing.Color.LightBlue;
}
}
How to create an Image Command Field Column and add to the GridView at runtime
if (!Page.IsPostBack)
{
CommandField cmdField = new CommandField();
cmdField.ButtonType = ButtonType.Image;
cmdField.SelectImageUrl = "~/Images/Home_Np1.GIF";
cmdField.ShowSelectButton = true;
cmdField.HeaderText = "Select";
GridView1.Columns.Add(cmdField);
GridView1.DataBind();
}

How to loop through all the rows in all the pages of a GridView
One simple way to loop through all the rows in all the pages of a GridView is to access its DataSource. In this example, we will loop through the SQLDataSource to retrieve all the rows in a GridView and access its cell value. You can modify the logic depending on the type of controls you have added to the GridView
C#
protected void Button1_Click(object sender, EventArgs e)
{
DataSourceSelectArguments dsaArgs = new DataSourceSelectArguments();
DataView view = (DataView)SqlDataSource1.Select(dsaArgs);
DataTable dt = view.ToTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string s = dt.Rows[i][j].ToString();
}
}
}

0 comments: