views:

3466

answers:

4

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.

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

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

Mehrdad Afshari
A: 

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.

Andrew Hare
A: 

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" %>
tanathos
I do too, not only for performance, but for static type checking. But for the sake of simplicity, I used Eval.
Mehrdad Afshari
A: 

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.

GoodEnough