Q:

Asp.net c# multiple value in a single column of gridview

How can I show multiple value in a single column of a GridView? For example when I search "Ivan" in the TextBox, the output will return multiple rows of Ivan like this:

Name Task
Ivan Task1
  Ivan Task2
  Ivan Task3

I want something like this

Name Task
Ivan Task1, Task2, Task3

My Table is like this

Employee (id,name)
  Task(id,name)
  EmployeeTask(employee.id,task.id)

Here is my sql code
SELECT  e.name,  t.name
FROM EmployeeTask et
INNER JOIN employee e ON e.id = et.employee_id
INNER JOIN task t ON t.id = et.task_id
WHERE e.name = @Name

And this is my GridView mark up
<Columns>
    <asp:BoundField DataField="name" HeaderText="Name" SortExpression="name"/>
    <asp:BoundField DataField="task" HeaderText="Task" SortExpression="task"/>        
</Columns>

A:

In pure SQL, here's a way to get your desired result which you can then feed into the GridView:
SELECT     e.name, REPLACE(REPLACE(REPLACE
                          ((SELECT     t.name
                              FROM         EmployeeTask AS et INNER JOIN
                                                    task AS t ON t.id = et.task_id
                              WHERE     (et.employee_id = e.id)
                              FOR XML RAW(''), ELEMENTS)
                   , '</name><name>', ', '), '<name>', ''), '</name>', '') AS EmployeeTasks
FROM         employee AS e
WHERE     (e.name = @Name)

Essentially, it's a subquery that flattens the tasks into XML output and then replaces the tags with commas.

