tags:

views:

395

answers:

2

I am using a GridView in asp.net 2.0 and I want to perform inline editing. I am using an object datasource. Because I want to use validation controls on the integer fields in my gridview, I have made them into <TemplateFields> and added a datatype validator and a range validator. This allows me to either have a blank field, or an integer value between 0 and 999.

I am trying to display a "-" when the value of the property is not defined. There is no Null for an integer, so I have decided to use -1 as the value to indicate a Null.

I am reformatting the to display the "-" if the value is -1. I do that as follows:

<ItemTemplate>
   <asp:Label ID="lblPC" runat="server" Text='<%# FormatIntegerToText(Eval("PitchCount"),"-") %>'></asp:Label>
</ItemTemplate>

In the code behind I have defined the function FormatIntegerToText as follows:

Protected Function FormatIntegerToText(ByVal value As Object, ByVal nullvalue As String) As String
       ' Make sure value is not null... if so, return "-"
       If value = Null.NullInteger() Then
           Return nullvalue
       Else
           Return value.ToString()
       End If
End Function

All of this works great. Now comes the problem...when I click my Edit button, the <EditItem> is displayed (with textboxes etc) but all the "null" values are displayed as -1

I currently have this as my <EditItemTemplate>

<EditItemTemplate>
   <asp:textbox ID="txtPC" runat="server" Text='<%# Bind("PitchCount") %>' width="25" Columns="2"></asp:textbox>
   ....a couple of validators....
</EditItemTemplate>

I though I could do the following to reformat the value that is placed in the text box:

<EditItemTemplate>
   <asp:textbox ID="txtPC" runat="server" Text='<%# FormatIntegerToText(Bind("PitchCount")) %>' width="25" Columns="2"></asp:textbox>

but when I do this I get a compilation error that Bind is not a recognized function.

My question is, why is this not allowed, and how can I work around it?

A: 

You might want to do this differently. Instead of using a bound column, create a template column... that will give you full control over the content, and allow you to write a function to format the text during display as well as set the contents to the appropriate value when editing.

RichO
A: 

Bind is not really a function, that's why you get compilation error. More details are at Eilon Lipton's Blog.

Try replacing Bind with Eval.

You also would need to store new value in RowUpdating event handler:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
   e.NewValues["PitchCount"] =
      ((TextBox)((GridView)sender).Rows[e.RowIndex].FindControl("txtPC")).Text;
}


Another approach is to use nullable type. Instead of Integer use Nullable(Of Integer). Then, use NullDisplayText property to show “-” instead of NULL:

<asp:BoundField DataField="PitchCount" NullDisplayText="-" HeaderText="PitchCount"
  SortExpression="PitchCount />
Pavel Chuchuva