开发者

dropdownlist value into asp:label

I have

public class ListA
{

   private string code;
   private string name;

   public string Code { get { return code; } set { cod开发者_StackOverflowe = value; } }
   public string Name { get { return name; } set { name = value; } }

}

I am populating the dropdownlist with code:name.

and I have an asp:label in which I want to show only Name that is selected in the dropdownlist.

How can I do that?


You will essentially need to create a function/method for handling the OnChange or OnSelectedIndexChange event for your dropdown. When the event is fired, your code should set the Text property of the label based upon the Text of your SelectedItem in the dropdown.

You could do this entirely in JavaScript, but this is a sample of how this can be done purely in the code behind... You could also look at integrating either UpdatePanels or some other form to make these changes asynchronously.

CODE BEHIND

protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    if(MyDropDown.SelectedIndex > -1)
    {
        MyLabel.Text = MyDropDown.SelectedItem.Text;
    }
}

FRONT END

<asp:DropDownList ID="MyDropDown" runat="server" AutoPostBack="True" 
    onselectedindexchanged="MyDropDown_SelectedIndexChanged" >
    <asp:ListItem Selected="True"></asp:ListItem>
    <asp:ListItem Value="Test1">Test1</asp:ListItem>
    <asp:ListItem Value="Test2">Test2</asp:ListItem>
    <asp:ListItem Value="Test3">Test3</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Label ID="MyLabel" runat="server" />


Set your DropDownList DataValueField = "Name"

and then use myLabel.Text = myDropDownList.SelectedValue;


if on a postback:

myLabel.Text = myDropDownList.SelectedValue;

if you want it to change immediately in the browser, when the user selects something different, you'll have to use javascript, such as this:

JavaScript:

function updateText(ddl, lblId) {
    var lbl = document.getElementById(lblId);
    lbl.innerHTML = ddl[ddl.SelectedIndex].value;
}

.NET:

myDropDownList.Attributes.Add("onchange", "updateText(this, '" + myLabel.ClientID + "');");

EDIT Completely besides the point, but since I see you're not using them: have you heard of auto properties? Since C#3.5, you can write that exact class using just the following code:

public class ListA
{
   public string Code { get; set; }
   public string Name { get; set; }
}


Create a subroutine that handles the OnSelectedIndexChanged event. Capture the selected value and set it to the text value of your label.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜