Monday, September 22, 2008

Filling a dropdownlist with LINQ


Partial Public Class _Default
Inherits System.Web.UI.Page

Dim northwind As New northwindDataContext()

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not IsPostBack Then
Dim categories = From categorie In northwind.Categories _
Select categorie
DropDownList1.DataSource = categories
DropDownList1.DataTextField = "CategoryName"
DropDownList1.DataValueField = "CategoryID"
DropDownList1.DataBind()
End If

End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim selectValue = DropDownList1.SelectedItem.Value
Dim products = From product In northwind.Products _
Where product.CategoryID = selectValue
GridView1.DataSource = products
GridView1.DataBind()
End Sub

End Class

The ASPX Page

<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
<hr />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>

No comments:

Post a Comment