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

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

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

      

Now I want (in code) to apply the width attribute to the "bar" for every line I create. How can I target these lines? The width attribute will be unique for each row, depending on the value in the database for that row.

+1


source to share


4 answers


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

      



If you like, you can change Eval("Width")

to an expression that calculates the width.

+3


source


You want to handle the GridView event RowCreated

. This happens immediately after the GridView creates each row and gives you programmatic access to the row and all the controls it contains.



Below is the MSDN page on this event.

0


source


I suggest you don't use Eval if you can, because it's a little slower. In such cases, I usually prefer to pass my datasource to its base type:

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

      

where yourCustomData

is the string type of your data source (i.e. element a List<>

).

This method is faster than Eval.

Edit: oh, don't forget to include in the page a link to the namespace containing yourCustomData

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

      

0


source


I suggest you connect your callback handler to the OnRowDataBound event. Each string binding raises an event that you can handle in your callback handler.

In this callback handler, you can get information about the element's anchor to the string and apply the width according to the values โ€‹โ€‹in your database.

0


source







All Articles