Question

I have a GridView that has 3 columns: FirstName, LastName and a TemplateField FullName where I string together FirstName and LastName.

Assuming calling DisplayFullName is the function I want to use to concatenate FirstName and LastName, how do I pass the row argument to the function and how to declare the parameter of the function? Thanks.

Here's my code for the FullName column:

        <asp:TemplateField HeaderText="FullName">
            <ItemTemplate>
                <%# DisplayFullName(???) %>
            </ItemTemplate>
        </asp:TemplateField>

Here's my declaration for the function:

protected string DisplayFullName(???)
  { ... }

The ??? are where I need help. OR do I need to pass the row at all? If each time DisplayFullName is called, the 'current' row is known. If so, how do I access the current row in DisplayFullName?

I simplified the operation for the sake of clarity of the question. In reality, there can be up to 20 values in the row I need and I want to do some calculations in the function called.

Was it helpful?

Solution

@RJIGO: You can use function like this:

<asp:TemplateField HeaderText="Name">
     <ItemTemplate>
        <%# DisplayFullName(Eval("FirstName"), Eval("LastName"))%>         
        </ItemTemplate>
     </asp:TemplateField>

and your code behind method will like this

  protected string DisplayFullName(object FirstName, object LastName)
  {
      return Convert.ToString(FirstName)+Convert.ToString(LastName);
  }

OTHER TIPS

I don't know why you are calling a function here to display full name. You can use like this in your code to achieve full name:

    <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <%#Eval("FirstName") %>&nbsp;<%#Eval("LastName") %>   
                </ItemTemplate>
            </asp:TemplateField>
</asp:TemplateField>

Had to post since nobody seemed to give you an answer that does exactly what you ask for - passing the row to a backend function.

Simply pass "Container.DataItem" to your function - this is the DataRow

<asp:TemplateField>
    <ItemTemplate> 
        <%# DisplayFullName(Container.DataItem) %>
    </ItemTemplate> 
</asp:TemplateField>

then in the CodeBehind you can manipulate it as a DataRowView:

public string DisplayFullName(object containerDataItem)
{
    string firstName = ((DataRowView)containerDataItem)["FirstName"].ToString();
    string lastName = ((DataRowView)containerDataItem)["LastName"].ToString();
    ...

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top