How to create a simple Master-Slave DataGrid






1.67/5 (6 votes)
Aug 11, 2004

63130
This article shows how to create a simple Master-Slave DataGrid.
Introduction
In this article, I will provide code sample on how to make a simple Master-Slave DataGrid
. First, add a DataGrid
on the page and make a "Select" column using property builder.
Master-Slave DataGrid in C# Code
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
// Binds the DataGrid
BindGrid();
}
}
public void BindGrid()
{
SqlCommand myCommand =
new SqlCommand("SELECT * FROM Categories",myConnection);
myCommand.CommandType = CommandType.Text;
try
{
// Opens database connection
myConnection.Open();
// Execute SqlCommand that returns datareader
SqlDataReader dr =
myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// Populate MasterGrid
MasterGrid.DataSource = dr;
// Binds MasterGrid to the page
MasterGrid.DataBind();
}
// Catch SqlException
catch ( SqlException SqlEx )
{
// TODO
}
// Catch general Exception
catch ( Exception ex )
{
// TODO
}
// Closes the database connection
finally { myConnection.Close(); }
}
// This event is fired when the Selection is made in MasterDataGrid
private void ViewSelectionDetails(object sender, System.EventArgs e)
{
// Gets the primary key value from the Master DataGrid
Int32 categoryID =
Convert.ToInt32(MasterGrid.SelectedItem.Cells[0].Text);
Label2.Text = categoryID.ToString();
// Sends the key to the Slave DataGrid
PopulateSlaveGrid( categoryID );
}
// This method populates Slave DataGrid
public void PopulateSlaveGrid(Int32 cID)
{
// SQL QUERY to view the selected Item details
string commandString =
"SELECT CategoryName,Description FROM Categories WHERE CategoryID="+cID;
// Make an instance of SqlDataAdapter and Assign it the query string
SqlDataAdapter ad = new SqlDataAdapter(commandString,myConnection);
// DataSet instance created
DataSet ds = new DataSet();
// Fill DataSet
ad.Fill(ds,"Categories");
try
{
// Opens database connection
myConnection.Open();
// Populate SlaveGrid
SlaveGrid.DataSource = ds;
// Binds SlaveGrid to the page
SlaveGrid.DataBind();
}
// Catch SqlException
catch ( SqlException SqlEx )
{
// TODO
}
// Catch general Exception
catch ( Exception ex )
{
// TODO
}
// Closes the database connection
finally { myConnection.Close(); }
}
}