In this article we will create a simple Master-Detail form using a GridView and DetailsView.IntroductionIn this article we will create a Master-Detail form using a GridView and a DetailsView. A Master-Detail form displays a master list and the details for the currently selected item. We will use a "Titles" table of a "Pubs" database to display a master list in a GridView and an "Authors" table to display author details of the currently selected book in the master list.Steps:
ConString retrieves connection string from the Web.config file named "ConString". BindGridView() method binds data to the GridView.private void BindGridView(){ con = new SqlConnection(ConString); CmdString = "SELECT Title_Id, Title FROM Titles"; cmd = new SqlCommand(CmdString, con); sda = new SqlDataAdapter(cmd);| dt = new DataTable(); sda.Fill(dt); GridView1.DataSource = dt.DefaultView; GridView1.DataBind();}
BindGridView sets Title_Id and Title of Titles table as the data source of the GridView. Add the following code to the HTML view of Default.aspx to set the properties of the GrieView:<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" AllowPaging="True" AllowSorting="True" DataKeyNames="Title_Id" onselectedindexchanged="GridView1_SelectedIndexChanged" onpageindexchanging="GridView1_PageIndexChanging"> <Columns> <asp:BoundField HeaderText="Book Title" DataField="title" /> </Columns></asp:GridView>
Here, the title id of the selected row is fetched in the TitleID and it is passed to the BindDetailsView method to fill the DetailsView with the author details of the selected title.private void BindDetailsView(string TitleID){ CmdString = "SELECT a.au_fname AS 'First Name', a.au_lname AS 'Last Name', a.Phone AS 'Phone', a.Address AS 'Address', a.city AS 'City', a.state AS 'State', a.Zip AS 'Zip' FROM authors a JOIN titleauthor t ON a.au_id=t.au_id WHERE t.title_id=@TitleID"; con = new SqlConnection(ConString); cmd = new SqlCommand(CmdString, con); cmd.Parameters.AddWithValue("@TitleID", TitleID); sda = new SqlDataAdapter(cmd); dt = new DataTable(); sda.Fill(dt); DetailsView1.DataSource = dt.DefaultView; DetailsView1.DataBind();}Here, the author details of the given title id is retrieved from joining the "Authors" and "TitleAuthor" table and is set as the data source of the DetailsView.
HeaderText property is used to set header text of the DetailsView.Paging is enabled also in the DetailsView as one book can have multiple authors that can be paged.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: