How to display a Master Detail data using DataGrid

Platform: ASP.NET| Category: DataGrid

<asp:datagrid id='DataGrid1' ShowHeader =false AutoGenerateColumns =true  runat='server'   DataKeyField='OrderId' OnItemDataBound='ItemDB'>
	<Columns>
		<asp:TemplateColumn >
			<ItemTemplate>
				<b><%#DataBinder.Eval(Container.DataItem,'OrderId')%></b>
			</ItemTemplate>
		</asp:TemplateColumn>
	</Columns>
</asp:datagrid>

VB.NET


Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	’ Put user code to initialize the page here
	cn = New SqlConnection('Server=localhost;uid=sa;pwd=;database=northwind')
	If Not Page.IsPostBack Then
		da = New SqlDataAdapter('SELECT orderid FROM orders', cn)
		ds = New DataSet
		da.Fill(ds, 'Orders')
		DataGrid1.DataSource = ds
		DataGrid1.DataBind()
	End If
End Sub ’Page_Load

Protected Sub ItemDB(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
	If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
		Dim dgDetails As New DataGrid
		Dim orderid As Integer = CInt(CType(e.Item.DataItem, DataRowView)('OrderID'))
		dgDetails.DataSource = GetOrderDetails(orderid)
		dgDetails.DataBind()
		e.Item.Cells(1).Controls.Add(dgDetails)
	End If
End Sub ’ItemDB

Function GetOrderDetails(ByVal id As Integer) As DataSet
	da = New SqlDataAdapter('SELECT * FROM [Order Details] where orderid=' + id.ToString, cn)
	ds = New DataSet
	da.Fill(ds, 'OrderDetails')
	Return ds
End Function ’GetOrderDetails

C#


SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	cn=  new SqlConnection ('Server=localhost;uid=sa;pwd=;database=northwind');
	if (!Page.IsPostBack)
	{
		da= new SqlDataAdapter ('SELECT orderid FROM orders   ', cn);
		ds= new DataSet ();
		da.Fill (ds, 'Orders');
		DataGrid1.DataSource = ds;
		DataGrid1.DataBind (); 
	}
}

protected void ItemDB(Object sender,DataGridItemEventArgs e   )
{
	if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem ))
	{
		DataGrid dgDetails = new DataGrid();
		int orderid  =(int) ((DataRowView)e.Item.DataItem)['OrderID'] ;
		dgDetails.DataSource = GetOrderDetails(orderid );
		dgDetails.DataBind();
		e.Item.Cells[1].Controls.Add(dgDetails);
	}
}

DataSet GetOrderDetails(int id )
{
	da= new SqlDataAdapter ('SELECT * FROM [Order Details] where orderid=  ' + id, cn);
	ds= new DataSet ();
	da.Fill (ds, 'OrderDetails');
	return ds;
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.