Monday, June 18, 2012

Set selected value of DropDownList in DataList EditItemTemplate


In Asp.Net the DataList supports Edit mode by means of configuring the controls in the EditItemTemplate.

For Textboxes, setting value in the Edit mode is straight forward, we can just set the Text property and the value will get displayed while editing the Item.

    <ItemTemplate>
      <asp:Label
ID="lblDesc"
runat="server"
Text='<%#Eval("DESC") %>'>
</asp:Label>
    </ItemTemplate>

    <EditItemTemplate>
      <asp:TextBox
ID="txtLogDescChange"
Text='<%#Eval("DESC") %>'
runat="server"
            MaxLength="250">
</asp:TextBox>
    </EditItemTemplate>

In the case of
DropDownList, it is not straight forward, we shall see on how to accomplish this.
In the View mode, we shall display the value selected in the DropDownList in a Label, so that is straight forward.

In the Edit mode, we have to add a Label, in addition to the actual dropdown list, the value of the selected item should be set to this label. We will use this in the DataList ItemDataBound event, to set the selected value for the DropDownList.

The code in the .aspx page is as follows.

  <ItemTemplate>
<asp:Label
ID="lblStatus"
runat="server"
Text='<%#Eval("STATUS") %>'>
</asp:Label>
   </ItemTemplate>

   <EditItemTemplate>
      <asp:Label
ID="lblStatusValue"
runat="server"
      Visible="false"
Text='<%#Eval("STATUS") %>'>
</asp:Label>
      <asp:DropDownList
ID="ddlStatus"
runat="server">
                <asp:ListItem Value="">Select</asp:ListItem>
                <asp:ListItem Value="New">New</asp:ListItem>
                <asp:ListItem Value="Open">Open</asp:ListItem>
                <asp:ListItem Value="InProgress">InProgress</asp:ListItem>
                <asp:ListItem Value="Closed">Closed</asp:ListItem>
      </asp:DropDownList>
    </EditItemTemplate>

Once this is done, navigate to the code-behind .aspx.cs file to the DataList’s ItemDataBound event. Find the DropDownList control, get the value set is the label control and set as the selected value for the DropDownList control.

protected void dlData_ItemDataBound(object sender, DataListItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.EditItem)
   {
      DropDownList ddlStatus = (DropDownList)e.Item.FindControl("ddlStatus");
      Label lblStatusValue = (Label)e.Item.FindControl("lblStatusValue ");
ddlStatus.SelectedValue = lblStatusValue.Text;
    }      
}

Here the values in the DropDownList, ddlStatus is set to the values which was stored in the Hidden label field lblStatusValue.

That’s it we have set the selected value for a DropDownList control, in the DataList in Edit mode.


Search Flipkart Products:
Flipkart.com

No comments: