Search code examples
c#asp.netgridviewitemtemplate

How to call C# method from itemTemplate gridview


I have gridview with 3 columns. I need to add one more column 'Share' to this gridview. Query is there is no 'Share' column in database , we are calculating it through C# method. I had method named SHARE(), here how can i pass the value of Share to itemTemplate lable.

    <Columns>
        <asp:BoundField DataField="MarketName" HeaderStyle-Width="60px"  HeaderText="Market" />
        <asp:BoundField DataField="Year" HeaderStyle-Width="60px" HeaderText="Year" />
        <asp:BoundField DataField="Type" HeaderStyle-Width="60px" HeaderText="Type" />
        <asp:BoundField DataField= "TotalVolume" HeaderStyle-Width="100px" HeaderText= "Total Volume" />
        <asp:TemplateField>
        <HeaderTemplate>
          <asp:Label ID="lable1" runat="server" Width="60px" Text="Share"></asp:Label>
        </HeaderTemplate>
        <ItemTemplate>
            <asp:Label ID="lblShare" runat="server" Text='<% #Share() %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>

Code:

    public void share()
    {
        float share = 0;
        int tot = 0;
        int vol = 0;
        c.cmd.CommandText = "Select * from MarketDetail";
        c.adp.Fill(c.ds,"vt");
        foreach (DataRow dr1 in c.ds.Tables["vt"].Rows)
        {
            tot = tot + Convert.ToInt32(dr1["TotalVolume"]);
        }
        foreach (DataRow dr2 in c.ds.Tables["vt"].Rows)
        {
            share = tot /Convert.ToInt32(dr2["TotalVolume"]);
          //how assign this 'Share' value to lable in grid //

        }

    }

Solution

  • Thanks all friends. Now my code is working fine. firstly my method returns single value (ie. last one) while I need to print for every totalValue. Here is my working code:

    <ItemTemplate>
      <asp:Label ID="lblShare" runat="server" Text='<%#share((Int32)Eval("TotalVolume"))%>'/>
     </ItemTemplate>
    

    and

       public string share(int tv)
       {
        float share = 0;
        float tot = 0;
        c.cmd.CommandText = "Select * from MarketDetail";
        c.adp.Fill(c.ds, "vt");
        foreach (DataRow dr1 in c.ds.Tables["vt"].Rows)
        {
            tot = tot + Convert.ToInt32(dr1["TotalVolume"]);
        }        
        share = tot /tv ;
        c.ds.Tables["vt"].Clear();
        return share.ToString() +"%";
    }