IntroductionIn this code snippet, I would like to show how to bind the dropdown list within listview. Because I have get some questions in codegain forums most of the readers asking how we could bind or dynamically add item into dropdownlist with ListView. So first I created a aspx page like followings, <asp:ListView runat="server" id="lvPopUp">
<InsertItemTemplate>
<tr runat="server">
<td>
<asp:DropDownList ID="cmbYears" runat="server">
</asp:DropDownList>
</td>
<td>
<asp:TextBox ID="txtFname" runat="server" Text='<%#Eval("FirstName") %>' Width="100px">First Name</asp:TextBox>
<asp:TextBox ID="txtLname" runat="server" Text='<%#Eval("LastName") %>' Width="100px">Last Name</asp:TextBox>
</td>
<td>
<asp:TextBox ID="txtCtype" runat="server" Text='<%#Eval("ContactType") %>' Width="100px">Contact Type</asp:TextBox>
</td>
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
</td>
</tr>
</InsertItemTemplate>
</asp:ListView>Now i have to load list of years in within dropdownlsit in InsertItemTemplate. so this point we have to choice right event to bind Years list within the control.if you re choice ItemDataBound events it won't bind. because this is raise after controls are created and databinding times. So we have to choice the ItemCreated event to bind data to year dropdown list.further reading about ItemCreated here Code protected void lvPopUp_ItemCreated(object sender, ListViewItemEventArgs e)
{if (e.Item.ItemType == ListViewItemType.InsertItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("cmbYears");if (ddl != null)
{
ddl.DataSource = LoadYear();
ddl.DataTextField = "Year";
ddl.DataValueField = "Value";
ddl.DataBind();
}
}
}In above event code, i'm checking ItemType before bound data to control, because we have to bind list of years which is the ItemInsertTemplate Dropdown list.I hope this is help to you all. thank you for reading. |