显示多个表的数据而不在C#中加入它们

时间:2015-02-24 15:08:02

标签: c# linq datagridview

我在C#中有一个DataGridView。在这里,我通过数据源显示一些足球运动员。我有一个表玩家,在这个表中也是每个玩家的teamId和countryId。例如,countryId 1代表比利时。这些id与其他表“Countries”中的正确countryname相关联。

现在我想知道是否可以在不加入表的情况下显示国家名称而不是id,因为我需要从DataGridView中获取一个Player-object来删除,编辑,...

我必须使用LINQ,而且我几乎都在硬编码。

PlayerForm代码(使用DGV)

public partial class PlayersForm : Form
{
    public PlayersForm(int id)
    {
        int teamId = id;
        InitializeComponent();
        DataClassesFPDataContext db = new DataClassesFPDataContext();
        var players = db.Players.ToList();
        dgvPlayersPerTeam.DataSource = players;
        var playersTeam = from player in players
                          where player.Team_TeamId == teamId
                          select player;
        dgvPlayersPerTeam.DataSource = playersTeam.ToList();

    }
}

现在我只显示玩家的所有信息,如下所示。 (由于声誉,不能在帖子中使用图片。)

https://drive.google.com/file/d/0Byl4uvHVXWkYU3AtQWtGdW1taFU/view?usp=sharing

1 个答案:

答案 0 :(得分:0)

解决了我自己的问题。我需要CellFormatting。现在,由于这种方法,countryId得到了改变。

private void dgvPlayersPerTeam_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        DataGridView dgv = (DataGridView)sender;
        if (dgv.Columns[e.ColumnIndex].Name == "Country_CountryId" &&
            e.RowIndex >= 0 &&
            dgv["Country_CountryId", e.RowIndex].Value is int)
        {
            DataClassesFPDataContext db = new DataClassesFPDataContext();
            var countries = db.Countries.ToList();
            int countryId = (int)dgv["Country_CountryId", e.RowIndex].Value;
            string countryFull = (from country in countries
                                  where country.CountryId == countryId
                                  select country.Full).First().ToString();

            e.Value = countryFull;
            e.FormattingApplied = true;
        }
    }