Sean Porteui
Sean Porteui

Reputation:

Working with GridView and ItemTemplates (ASP.net/C#)

I have a GridView that is populated via a database, inside the GridView tags I have:

<Columns>
  <asp:TemplateField>
    <ItemTemplate><asp:Panel ID="bar" runat="server" /></ItemTemplate>
  </TemplateField>
</Columns>

Now, I want to be able to (in the code) apply a width attribute to the "bar" panel for each row that is generated. How would I go about targeting those rows? The width attribute would be unique to each row depending on a value in the database for that row.

Upvotes: 1

Views: 6757

Answers (4)

mbillard
mbillard

Reputation: 38852

I suggest you attach a callback handler to the OnRowDataBound event. Each row binding will fire an event which you can handle in your callback handler.

In that callback handler, you can get the info about the item being bound to the row and apply the width according to the values in your database.

Upvotes: 0

tanathos
tanathos

Reputation: 5606

I suggest you to not use Eval, if you can, because it's a little slower. In that cases I generally prefer to cast my data source to his base type:

<Columns>
  <asp:TemplateField>
    <ItemTemplate>
    <asp:Panel ID="bar" runat="server" Width='<%# ((yourCustomData)Container.DataItem).Width %>' />
    </ItemTemplate>
  </TemplateField>
</Columns>

where yourCustomData is the row type of your data source (i.e. the element of a List<>).

This method is really faster than Eval.

Edit: oh, don't forget to include in the page a reference to the namespace that contains yourCustomData

<%@ Import Namespace="yourNameSpace.Data" %>

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351526

You are going to want to handle the GridView's RowCreated event. This occurs just after the GridView creates each row and will give you programmatic access to the row and all the controls contained within it.

Here is the MSDN page on the event.

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422026

<asp:Panel ID="bar" runat="server" Width='<%# Eval("Width") %>' />

If you like, you can change Eval("Width") to the expression that calculates the width.

Upvotes: 3

Related Questions