Friday, September 10, 2010

How to Bind Data to a DataGrid Control Using ASP.Net and VB.Net,How To Bind Data In Datagrid From Database?

DataGrid control. 

Html Source Code : 
<asp:Label ID="lblOrderDetails" Runat="server" /><br><br>



<asp:DataGrid ID="dgDisplayData" Runat="server" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3" GridLines="Vertical" AutoGenerateColumns="True" AllowPaging="True" AllowSorting="True">

 <FooterStyle ForeColor="Black" BackColor="#CCCCCC" />

 <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#008A8C" />

 <AlternatingItemStyle BackColor="#DCDCDC" />

 <ItemStyle ForeColor="Black" BackColor="#EEEEEE" />

 <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#000084" />

 <PagerStyle HorizontalAlign="Right" ForeColor="Black" BackColor="#999999" />

asp:DataGrid><br>



<hr align="left" width="375" size="1">


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

    DBConn.Open()

    If Not IsPostBack Then

      DBAdap = New SqlDataAdapter("Select OrderID from Orders", DBConn)

      DBAdap.Fill(DS, "Orders")

      ddlSelectOrder.DataSource = DS.Tables("Orders").DefaultView

      ddlSelectOrder.DataBind()

      ddlSelectOrder.Items.Add(New ListItem("", ""))

      ddlSelectOrder.SelectedValue = ""

    End If

End Sub


Now bind DataGrid control when the value is selected from the DropDownList control. The event used for this task is ddlSelectOrder_SelectedIndexChanged:



Private Sub ddlSelectOrder_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlSelectOrder.SelectedIndexChanged



    Dim orderID As Integer

    If ddlSelectOrder.SelectedValue = String.Empty Then

      lblOrderDetails.Text = ""

      dgDisplayData.DataSource = Nothing

      Me.DataBind()

      Exit Sub

    End If

    orderID = ddlSelectOrder.SelectedValue

    lblOrderDetails.Text = "Order's Detail is as follows:"

    DBAdap = New SqlDataAdapter("SELECT * From OrderDetails WHERE OrderID = " & orderID, DBConn)

    DBAdap.Fill(DS, "OrderDetails")

    dgDisplayData.DataSource = DS.Tables("OrderDetails").DefaultView

    dgDisplayData.DataBind()



End Sub