Binding template field in GridView control from Data coming from another field other than the foreign in other table

I have a gridview control. In the attahced  script,there is a template  in which I am Binding company name.
It works fine, but I don't  want this value. it picks the comapny Name in other table named Companies

The table companies has three important fields
BelongstocompanyId .(  is a subset of company ids are company)

Bind("CompanyName") is getting the information fon the basis of comapnyID,  but i want that  to pick  first belongstocompanyId and on that basis  pick comapnyId, and then CompanyName
asp:GridView ID="gvEvents" AutoGenerateColumns="false" HeaderStyle-HorizontalAlign="Left" HeaderStyle-CssClass="dataTable_Header" CellPadding="2" RowStyle-CssClass="dataTable_Item" BorderColor="#666666" runat="server">
        <asp:BoundField DataField="EventName" HeaderText="Arrangementnavn" />
        <asp:BoundField DataField="EventCode" HeaderText="Arr.kode" />
           <HeaderTemplate>Kontonavn </HeaderTemplate>
         <asp:Label ID="lblCompany" runat="server" Text='<%# Bind("CompanyName")%>'></asp:Label>


Open in new window

Ammar IqbalSenior IT Consultant/senior Software engineerAsked:
Who is Participating?
For this you have to update your data-source in such a way that, take column name in data-source itself (sql query, if you are using) with alias name.
And bind this alias name into your gridview column template.

sql eg.
select companyname, companyid, companyname as ParentCompanyName
from <tablename>

then update your gridview temaplate as:

<asp:Label ID="lblCompany" runat="server" Text='<%# Bind("ParentCompanyName")%>'></asp:Label>

Hope this helps you.
Ammar IqbalSenior IT Consultant/senior Software engineerAuthor Commented:
In my Datasource to Table "Events". which has a foreign key companyId  ,.This company id is connecting to the companeis table. Thats  why its binding CompanyName on the basis of companyID, but I want that it should pick BelongstoComapnyId another columni n comapnies tables (but it  is a subset of companyid as well. for example if it contains 1002, then this  1002 exists as comapnyID-primary key in someother row of the same table Companeis, and after that I can get and display CompanyName in it)
I agree with mroonal, this should come from your datasource which should use a subquery or recurvise call depending on its capability.

for SQL try..
SELECT A.companyID, C1.CompanyName, A.BelongsTocompanyID
  FROM (SELECT companyID, BelongsTocompanyID 
          FROM Events, company C
         WHERE Events.companyID = C.companyID
            -- Place other criteria here
        ) A,
        company C1
 WHERE A.BelongsTocompanyID = C1.companyID

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.