Wednesday, 6 June 2012

Editable DropDownlist

Introduction

In ASP.Net Dropdownlist control cannot be editable by default. We can easily overcome this problem. This article is used to overcome this issue.

Using the code

Create one blank asp.net web page(Default.aspx) and include one textbox and dropdownlist control. see the following code.
<asp:TextBox ID="txtDisplay" runat="server"></asp:TextBox>

<asp:DropDownList ID="ddSelect" runat="server">

    <asp:ListItem Value="test1" >test1</asp:ListItem>

    <asp:ListItem Value="test2">test2</asp:ListItem>

</asp:DropDownList>
        
After inserted this controls into web page we need to set the following style into textbox control.
style="position:absolute"  
The position property places an element in a static, relative, absolute or fixed position. There are four types of position like static, relative, absolute and fixed.

Value Description
static Default. An element with position: static always has the position the normal flow of the page gives it (a static element ignores any top, bottom, left, or right declarations)
relative An element with position: relative moves an element relative to its normal position, so "left:20" adds 20 pixels to the element's LEFT position
absolute An element with position: absolute is positioned at the specified coordinates relative to its containing block. The element's position is specified with the "left", "top", "right", and "bottom" properties
fixed An element with position: fixed is positioned at the specified coordinates relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties. The element remains at that position regardless of scrolling. Works in IE7 (strict mode)
<asp:TextBox style="position:absolute" ID="txtDisplay" runat="server"></asp:TextBox>  

After adding the position style we need to set the equal width for both textbox and dropdownlist control.
<asp:TextBox style="width:120px;position:absolute" ID="txtDisplay" runat="server"></asp:TextBox>

<asp:DropDownList ID="ddSelect" style="width:140px" runat="server">

<asp:ListItem Value="test1" >test1</asp:ListItem>

<asp:ListItem Value="test2">test2</asp:ListItem>

</asp:DropDownList>

After adding the Styles we need to create javascript function. This function is used to display the selected dropdwon 
text into textbox control.

<script language="javascript" type="text/javascript">

function DisplayText()
{
    document.getElementById("txtDisplay").value = document.getElementById("ddSelect").value;
    document.getElementById("txtDisplay").focus();
}
</script> 
After adding the javascript function. use this function for Dropdown change event fires. 
Add the following code into Default.aspx.cs file.

protected void Page_Load(object sender, EventArgs e)
{
 ddSelect.Attributes.Add("onChange", "DisplayText();");
}

No comments:

Post a Comment