如何组合来自2个源的列并绑定到GridView

时间:2014-03-06 00:42:19

标签: c# asp.net linq-to-sql

我有: 1 Datatable - EmployeeAccess& 1视图 - View_HCM

两者都有相同的列(EmpNo),View_HCM有1000多个数据,其中EmployeeAccess只有4个数据。 View_HCM有电子邮件地址字段,EmployeeAccess没有。我需要根据4个数据从View_HCM获取电子邮件地址。

public List<EmployeeAccess> EmployeeAccess2()
{
    EmployeeAccess EA = new EmployeeAccess();
    View_HCM VH = new View_HCM();

    var x = from b in contxt.View_HCM
            where b.EmpNo == EA.EmpNo
            select b.EmailAddress;

    return x.ToList();
}

我收到了这个错误:

Cannot implicitly convert type 'Systems.Generic.Collections.String<string>' to ... '< list >'

1 个答案:

答案 0 :(得分:1)

您的退货类型有误。

要修复错误,请更改返回的类型:

public List<string> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();

var x = from b in contxt.View_HCM
        where b.EmpNo == EA.EmpNo
        select b.EmailAddress;

return x.ToList();
}

要在gridview中显示电子邮件地址,您可以这样做

使用单个命名字段定义一个类:

public class EmailRecord
{
public string EmailAddress{ get; set; }
}


public List<EmailRecord> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();

var x = from b in contxt.View_HCM
        where b.EmpNo == EA.EmpNo
        select new EmailRecord
{
    EmailAddress = b.EmailAddress
};

return x.ToList();
}

绑定你的网格

gridEmployeeAccess.DataSource = TAClass.EmployeeAccess2(); gridEmployeeAccess.DataBind();

在aspx中:

<asp:GridView ID="gridEmployeeAccess" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="EmailAddress" headertext="Email Address"/>
    </Columns>
</asp:GridView>