Thursday, 6 December 2012

DROPDOWN LIST BINDING AND SELECTED INDEX CHANGE EVENT

CREATE A TABLE

CREATE TABLE Nametable
(
    [Nameid] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL
)

IN THE ASPX PAGE

   <form id="form1" runat="server">
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
        onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
    </asp:DropDownList>
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
   </form>

IN THE ASPX.CS PAGE (dropdown binding and selected index change event)
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class Default7 : System.Web.UI.Page
{
    //Configuring the connection string and calling it from web.config
    static string sathya = ConfigurationManager.ConnectionStrings["SQLCON"].ConnectionString;
    SqlConnection satcon = new SqlConnection(sathya);
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            binddrop();
        }
    }
//Binding the dropdown list with the sql database
    private void binddrop()
    {
        satcon.Open();
        da = new SqlDataAdapter("select * from Nametable",satcon);
        DataSet ds = new DataSet();
        da.Fill(ds);
        satcon.Close();
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Nameid";
        DropDownList1.DataBind();
    }
//SelectedIndexChanged event displaying the number according the name selected in the dropdown list
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int Nameid = Convert.ToInt32(DropDownList1.SelectedValue);        satcon.Open();
        SqlCommand cmd = new SqlCommand("select * from Mobiletable where Nameid=" + Nameid , satcon)
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        TextBox1.Text = dr["Number"].ToString(); //Displaying the output filed "Number" in the texbox
        satcon.Close();
       }
}

No comments:

Post a Comment

back to top