When fielding a few questions on the ASP.Net Forums I ran across a question that I’d recently read about going through the ASP.Net 2.0 Wrox book. The question was how do I access the row values from a databound grid without having access to the original data source. The person then went on to ask whether they’d be able to pass the DataBinder class object to the code behind to have access to the static Eval() method for the entire row of data.
Normally in the markup you see most of the databound code examples will have a function that accepts an input value that is called from the markup, passed to the code-behind, and then the code behind will output a formatted value back to the markup. It works well for situations where you need to calculate values quickly without the original data source, or to quickly format values for display purposes on databinding the control to a datasource.
Passing a Single Eval DataItem
ASPX
<%# GetTotalValue(Eval("ColumnName")) %>
CS
protected int GetTotalValue(object total)
{
int value = 0;
int.TryParse(Convert.ToString(total), out value);
return value;
}
In cases where multiple row values need to be accessible without having to pass each value directly one could simply access the databound row from the code-behind during the binding of the data control. In this case we still have the markup call to the code-behind as seen in the ASPX section below. This time we’re not passing any value(s), but instead we’ll just call them as we need them on the code-behind. Yes, it’s that simple. As you can see below we simply call to the DataBinder.Eval static function, pass in the data container (exposed by the Page,) and then simply supply the name of the column from the datasource we want. This is not limited to a single column, but only to a single row of data at a time.
Accessing Multiple DataItems
ASPX
<%# GetTotalValue() %>
CS
protected int GetTotalValue()
{
int value = 0;
int.TryParse(Convert.ToString(DataBinder.Eval(Page.GetDataItem(), "ColumnName")), out value);
return value;
}
The reason this is limited to a single row is that we’re only able to access these values during data binding event, which is indcated per the ‘<%#’ on the markup side indicating that this function will only be called when the form is binding. Each row will call the same function outputting the unique formatting of the columns or calculations being performed on the code-behind calls. There is no need to try to pass the DataBinder, pass the datacontainer, or anything of the sort because it’s already available to us. Now keep in mind that you can’t call the GetTotalValue() anytime you’d like as this function will only work during the the databound event of the control.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5