Sabtu, 14 September 2013

How to access Text property , Value ,Index from DropDownList in ASP.NET

Top article

Introduction


Text Property : you can access or set the item text which is in DropDownList. If you want to access the text of the DropDownList then simply you can use
String var=DropDownList1.items[i].Text; (this is correct)
Here items[i] is directly denote to collection so you can not use 
String var=DropDownList1.items.Text;  ( This is incorrect)
If you want to add items to the DropDownList , simply you can use add method 
DropDownList1.Items.Add("hello");

Lets take an example to access index,Text and value of the selected item in DropDownList

In above mentioned top article we learn how to bind DropDownList with XmlDataSource in ASP.NET. Also this example show that how to access the text of DropDownList.
<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Text += "Your Selected value is <br/>" + DropDownList1.SelectedValue;
        Label1.Text += "<br/> Your Selected Text is <br/>" + DropDownList1.SelectedItem.Text;
        Label1.Text += "<br/> Your Selected Item Index is <br/>" + DropDownList1.SelectedIndex.ToString();
     
     
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="XmlDataSource1" DataTextField="Text" DataValueField="url" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        </asp:DropDownList>
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile.xml"></asp:XmlDataSource>
 
    </div>
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </form>
</body>
</html>

Output
How to access Text property , Value ,Index from DropDownList in ASP.NET

Tidak ada komentar:

Posting Komentar