Search code examples
c#asp.netgridviewhashtableitemtemplate

How to Bind the data from a Hashset to ItemTemplate in asp.net c#


I created item template inside a GridView.

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" 
    CellPadding="3" GridLines="Horizontal" onrowdatabound="GridView1_RowDataBound" >
    <AlternatingRowStyle BackColor="#F7F7F7" />
    <Columns>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Enabled='<%# Eval("id") %>' 
                    Text="Label"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

Now my issue is I am storing the "id" in a hash set because I have some duplicate ID's and I want to display only unique ID's

var id = new HashSet<String>();
id.Add("1");
id.Add("1");
id.Add("2");
id.Add("3");
id.Add("4");
id.Add("5");
Gridview1.DataSource=id;
Gridview1.DataBind();

I think something is worong with the Eval method and I don't think it is getting the value from Hashset.

Can somebody explain me how to bind the data from Hashste to Eval?

Also, it was working if I dint use ItemTemplate, I mean I can just fill the gridiew directly from Hashset value. However, I am trying to make nested gridview hence using Item Template.

Let me know if you have any questions.


Solution

  • Just because you name a variable id the underlying type does not contain a property id.

    You could use an anonymous type as DataSource:

    var ids = new HashSet<String>();
    ids.Add("1");
    ids.Add("1");
    ids.Add("2");
    ids.Add("3");
    ids.Add("4");
    ids.Add("5");
    Gridview1.DataSource = ids.Select(id => new { id }).ToList();
    Gridview1.DataBind();
    

    However, you are trying to set a boolean property (Enabled) from an Id. That seems to be incorrect.

    (note that i've changed the name of the HashSet from id to ids since it contains multiples)