Search code examples
asp.netgridviewitemtemplate

Data not available in GridView ItemTemplate field onPreRender


I have this scenario.

An ascx contains this GridView:

<asp:GridView ID="dataTable" runat="server" >
    <Columns>
        <asp:TemplateField HeaderText="Key">
            <ItemTemplate>
                <%# ((KeyValuePair<string, string>)(Container.DataItem)).Key%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Value">
            <ItemTemplate>
                <%# ((KeyValuePair<string, string>)(Container.DataItem)).Value%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

I'm loading a fake Array into the GridView during the Page_Load

var values = new Dictionary<string, string>();
values.Add("test1", "2");
values.Add("test2", "2");

dataTable.DataSource = values;
dataTable.DataBind();

If during the OnPreRender I try to check the value of

dataTable.Rows[0].Cells[0].Text

It has no value. Then the grid is rendered perfectly and every value is in place. Is there any way to fix this?


Solution

  • You can put a label control like this:

        <asp:TemplateField HeaderText="Key"> 
            <ItemTemplate>
                <asp:Label runat="server" Text="<%# ((KeyValuePair<string, string>)(Container.DataItem)).Key%>"></asp:Label>
            </ItemTemplate> 
        </asp:TemplateField>
    

    And then access the value like this on the user control´s PreRender:

        protected void Page_PreRender(object sender, EventArgs e)
        {
            Label lbl = dataTable.Rows[0].Cells[0].Controls[1] as Label;
            string t = lbl.Text;
        }
    

    Or like this on the consumer page´s PreRender:

        protected void Page_PreRender(object sender, EventArgs e)
        {
            GridView dataTable = dataTableWebUserControl1.FindControl("dataTable") as GridView;
            Label lbl = dataTable.Rows[0].Cells[0].Controls[1] as Label;
            string t = lbl.Text;
        }