The Self-Taught Programmer

Recipes from real-world experience with asp.net.

Posts Tagged ‘GridView

How to get the value from a GridView column on RowDeleting

leave a comment »

The Situation:

You need to get the value of one of the columns in the row you are deleting in a GridView to do some processing before the row is deleted.

A Solution:

When using the RowDeleting method, you cannot use e.Row.Cells[1].Controls[1] to get the control in that cell like you can in the RowCreated method. Instead, you can simply access the text of the desired cell and convert it to whatever datatype you need, like this:

protected void gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
	// You get the Key (identity value) of the row like this...
	string userName = gridview1.DataKeys[e.RowIndex].Value.ToString();
	
	// And you can get the value of any other cell in the row like this... 
	// (this would get the value in the 4th cell)
	string cellval = gridview1.Rows[e.RowIndex].Cells[3].Text;
	
	// DO MORE PROCESSING HERE
}
Advertisements

Written by Jim McMullen

June 19, 2012 at 3:51 pm

Posted in How-To

Tagged with

How To Avoid Null Reference Exceptions in an ASPX File When Dynamically Populating a GridView or ListView Control

leave a comment »

The situation:

You have a GridView control with a TemplateField in your ASPX page that is dynamically populated from a database. You of course use an Eval() statement to dynamically populate the TemplateField, but the db field is nullable (and in fact contains a null value), and when you run the page, you get an NullReferenceException because you are trying to bind to a null value.

This is your basic (simplified) code that is causing the error (because “Cost” is null):


<asp:GridView id="MyGridView"
	DataSourceID="MyDataSource1"
	Runat="Server">
	<Columns>
		<asp:TemplateField HeaderText="Cost">
			<ItemTemplate>
				<%# Eval("Cost") %>
			</ItemTemplate>
		</asp:TemplateField>
	</Columns
</asp:GridView>

Here is the fix: Add this method to your codebehind:


	protected string CheckNull(object objGrid)
	{
		if ( object.ReferenceEquals(objGrid, DBNull.Value) )
		{
			return "not available";
		}
		else if ( objGrid == null )
		{
			return "not available";
		}
		else
		{
			return objGrid.ToString();
		}
	}

You can change “not available” to any value you wish.

Then your template field should be changed to:


<%# CheckNull(Eval("Cost")) %>

And that should fix the issue.

Written by Jim McMullen

May 3, 2011 at 2:40 pm