0
Posted on 3:02 AM by prajeesh and filed under ,
Working with Gridview inside Gridview.

Grid view is a very useful and easier to use data presentation control in asp.net it is having lots of default features that we can set very easily, but in some of the projects you may need to show a master client relationship to the users For eg:- List of students who are studying in different departments.
We can handle this situation by using nested grid views, ie a Gridview inside a Gridview.
Microsoft is providing a solution for this situation msdn website , see the link : http://msdn.microsoft.com/en-us/library/aa992038(VS.80).aspx

I think Microsoft's solution contains lot of steps to complete the process, I done a workaround on this and come up with a solution, let me explain the tasks in step by step with an example.
Step 1:
Create a gridview named gvDepartments and add a Template Field in it.
Step 2:
Inside the Template Field'd Item Template add another gridview called gvStudents.
Step 3:
Add following code in gvStudents grid view
DataSource ='<%# GetStudentInfo( Convert.ToInt16(Eval("Department_Id")) ) %>'
Where GetStudentInfo is a server side function that returns a datatable containing the list of students based on department id.
Source of the Grid views will be like below code :

DataKeyNames="DepartMent_Id" CellPadding="4" ForeColor="Black"
GridLines="Vertical" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px">




<%# Container.DataItemIndex+1 %>





DataSource ='<%# GetStudentInfo( Convert.ToInt16(Eval("Department_Id")) ) %>'
CellPadding="4" ForeColor="#333333" GridLines="None" ShowHeader="False"
AutoGenerateColumns="False">




<%# Container.DataItemIndex +1 %>






















Step 4
Create Method to bind gvDepartments (Must contain a column named “Department_Id” as we are passing this parameter to bind gvStudents).
Step 5
Create a Method named GetStudentInfo(int department_Id) , It accepts Department_Id as parameter and returns a
datatable contains students list,(example given below) and you are done.

public DataTable StudentsByDepartment(int DepartmentId)
{
SqlConnection dbConnection = new SqlConnection(ConnectionString);
DataTable dtStudentList = new DataTable();
try
{
dbConnection.Open();
SqlDataAdapter daStudents = new SqlDataAdapter();
SqlCommand cmdSelect = new SqlCommand("SelectStudentByDep",dbConnection);
cmdSelect.CommandType = CommandType.StoredProcedure;
cmdSelect.Parameters.AddWithValue("@Dep", DepartmentId );
daStudents.SelectCommand = cmdSelect;
daStudents.Fill(dtStudentList);
}
catch (Exception objException)
{
HttpContext.Current.Response.Write(objException.Message);
}
finally
{
if (dbConnection != null && dbConnection.State == ConnectionState.Open)
{
dbConnection.Close();
}
}
return dtStudentList;
}


Figure: Sample output of a nested Gridview :

Shout it kick it on DotNetKicks.com
0
Responses to ... Creating a Nested Gridview Control