I am your master and I like to command my child. As you have already guessed this article is about Master-Child GridView control. The idea behind this is pretty simple. You have a master GridView control which is when clicked displays the information in the child GridView. Let's see how this can be done.

 

Introduction:

I am your master and I like to command my child. As you have already guessed this article is about Master-Child GridView control. The idea behind this is pretty simple. You have a master GridView control which is when clicked displays the information in the child GridView. Let's see how this can be done.

Creating the Master GridView Control:

Our master GridView will contain the PersonID and Name. "PersonID" is the primary key in the Person table and also the foreign key in the Phone table. In real world scenario you will never display the primary key, this can be done by making the "PersonID" column invisible. For more information on how to retrieve the value from an invisible column please visit Retrieving values from invisible column. I have added a "Select" column which let's me select values of particular rows of GridView control. The code below is implemented in the SelectedIndexChanged event of the master GridView control.

protected void gvMaster_SelectedIndexChanged(object sender, EventArgs e)

{

int personID = (int) gvMaster.SelectedValue;

// Send the value to the database to fetch the results

FetchPersonDetails(personID);

}

We retrieve the "PersonID" from the master GridView and send it to FetchPersonDetails method which in turn populates the child GridView.

private void FetchPersonDetails(int personID)

{

string connectionString = @"Data Source=localhost;Initial Catalog=MyDatabase;Integrated Security=True";

SqlConnection myConnection = new SqlConnection(connectionString);

SqlCommand myCommand = new SqlCommand("SELECT * FROM tblPhone WHERE PersonID = @PersonID", myConnection);

myCommand.Parameters.AddWithValue("@PersonID", personID);

SqlDataAdapter ad = new SqlDataAdapter(myCommand);

DataSet ds = new DataSet();

ad.Fill(ds, "tblPhone");

gvChild.DataSource = ds;

gvChild.DataBind();

}

All we do is we send the "PersonID" to the database and retrieve the values from the "Phone" table.

Please keep in mind that it is not a best practice to access database each time a row is selected. For this reason you can cache the data and access Cache object instead of database. You can update the Cache object when the information in the Database is changed.    

I hope you like the article, happy coding !