Monday, January 26, 2009

Let's Talk about .. Visual Studio 2005-Bind DropDownList when another DropDownList changed in Repeater

P'Beer teached me last week about how to create the drop down list B that will be binded only when drop down list A's index is changed, for the case that A and B are drop down lists in the repeater.

The Instruction to Bind DropDownList when another DropDownList changed in Repeater

-add these tags for AJAX Update Panel

[HTML]
//asp:ScriptManager ID="ScriptManager1" runat="server">
/ /asp:ScriptManager>
//asp:UpdatePanel ID="UpdatePanel1" runat="server">
"

[..your table/tr/td..]

// /ContentTemplate>
// /asp:UpdatePanel>

-Add drop down list tags

[HTML]
Drop Down List A
Drop Down List B

-In the code behind, in Sub of Repeater_ItemDataBound, bind the drop down list A by adding the following lines.

[VB.Net]
If e.Item.DataItem.A_Code <> "" Or e.Item.DataItem.A_Code IsNot Nothing Then

ddlA.SelectedValue = e.Item.DataItem.A_Code

Else
'Bind DropDownList A
ddlA.DataTextField = "Ar_Name"
ddlA.DataValueField = "A_Code"
ddlA.DataSource = (New [YourNameSpace].[YourEntity].[ABus]).GetAll_ListA()
ddlA.DataBind()
ddlA.Items.Insert(0, "") 'if you don't wanna show the first choice.

End If

-Add the event for drop down list A's seelcted index changed.

[VB.Net]
#Region " DropDown Event "
Public Sub ddlA_SelectedIndexChanged(ByVal Sender As Object, ByVal e As System.EventArgs)
Dim x As String = CType(Sender, DropDownList).ClientID


For i As Integer = 0 To Me.repMain.Items.Count - 1


Dim ddlA As DropDownList = Me.repMain.Items(i).FindControl("ddlA")
If ddlA.ClientID = x Then
Dim ddlB As DropDownList = Me.repMain.Items(i).FindControl("ddlB")
'Bind DropDownList B
ddlB.DataTextField = "B_Name"
ddlB.DataValueField = "B_Code"
ddlB.DataSource = (New [YourNameSapce].[YourEntity].[YourBus]).Get_List_B_By_A_Code(ddlA.SelectedValue)
ddlB.DataBind()
End If
Next
End Sub

#End Region

No comments: