将多个记录分组并更新为一个gridview行

时间:2013-08-08 07:05:02

标签: asp.net vb.net gridview checkbox telerik

我需要增强应用程序并且表结构无法修改。

表格结构:

ID      StaffID     Type
========================
1       1           1
2       1           2   
3       1           3
4       2           2
5       2           3
6       3           1

我想将相同的StaffID分组到一个gridview行中,然后根据“Type”列的值对该复选框(Type 1,Type 2,Type3)进行数据绑定。

建议的Gridview:

StaffID     StaffName   Type 1  Type 2  Type 3
==============================================
1           Amy         [X]     [X]     [X]
2           John        [ ]     [X]     [X]
3           Chris       [X]     [ ]     [ ]

此外,如果用户选中/取消选中gridview中的复选框,如何插入/删除记录? 感谢。

1 个答案:

答案 0 :(得分:0)

这在我看来更像是一个SQL问题所以我会相应地回答它。如果您不是在寻找基于SQL的答案,请在问题中更清楚。如果您愿意,请修改您的标签。

只要类型的数量是固定且已知的,以下SQL就可以构成您的基础SQL查询(假设源是SQL数据库):

SELECT a.StaffID, Name, 
    CASE WHEN b.ID IS NOT NULL THEN 1 ELSE 0 END AS Type1,
    CASE WHEN c.ID IS NOT NULL THEN 1 ELSE 0 END AS Type2,
    CASE WHEN d.ID IS NOT NULL THEN 1 ELSE 0 END AS Type3
FROM dbo.Staff a
LEFT JOIN dbo.StaffType b ON a.StaffID = b.StaffID AND b.TypeID = 1
LEFT JOIN dbo.StaffType c ON a.StaffID = c.StaffID AND c.TypeID = 2
LEFT JOIN dbo.StaffType d ON a.StaffID = d.StaffID AND d.TypeID = 3

在GridView中,每个复选框都会知道其StaffID(来自行)和TypeID(来自列),因此只需处理其OnChanged事件并调用类似的内容:

DECLARE @StaffID INT = 1, @TypeID INT = 1

IF EXISTS (SELECT * FROM dbo.StaffType WHERE StaffID = @StaffID AND TypeID = @TypeID)
    DELETE FROM dbo.StaffType WHERE StaffID = @StaffID AND TypeID = @TypeID
ELSE
    INSERT INTO dbo.StaffType ( StaffID, TypeID )
    VALUES ( @StaffID, @TypeID )

更新了LINQ版本:

var q2 =
    from staff in staffList
    from type1 in typesList
        .Where(t => t.StaffID == staff.StaffID && t.TypeID == 1)
        .DefaultIfEmpty()
    from type2 in typesList
        .Where(t => t.StaffID == staff.StaffID && t.TypeID == 2)
        .DefaultIfEmpty()
    from type3 in typesList
        .Where(t => t.StaffID == staff.StaffID && t.TypeID == 3)
        .DefaultIfEmpty()
    select new
    {
        StaffID = staff.StaffID,
        Name = staff.Name,
        Type1 = (type1 != null),
        Type2 = (type2 != null),
        Type3 = (type3 != null)
    };