Monday, 22 July 2013

Asp.net Get dropdownlist selectedIndex using C#.net

As per previous articles we knew how to get the selected value or text from drop down. Now we will know how to get selected Index of dropdownlist. To do this task i have placed one Drop down and button.In the below code first i make selection on drop down then click on the button .It will print the Index value

<title>Get DropdownList selectedIndex in asp.net</title>
</head>
<body>
<form id="dynamicIndex" runat="server">
<div>
<asp:DropDownList ID="ddlIndex" runat="server">
</asp:DropDownList>
<asp:Button id="btnGetSelectedIndex" runat="server" Text="GetselectedIndex"
onclick="btnGetSelectedIndex_Click" />
</div>
Code behind:
public partial class GetDropdownSelectedIndexDB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
PopulateddlIndexDB();
}
}
protected void btnGetSelectedIndex_Click(object sender, EventArgs e)
{
int DdlselectedIndex=ddlIndex.SelectedIndex;
Response.Write(DdlselectedIndex.ToString());
}
private void PopulateddlIndexDB()
{
try
{
SqlConnection cni = new SqlConnection(ConfigurationManager.ConnectionStrings["DdlIndexConnectionString"].ToString());
cni.Open();
SqlDataAdapter cai = new SqlDataAdapter("select *from ContentType", cni);
DataSet cdi = new DataSet();
cai.Fill(cdi, "Content");
ddlIndex.DataSource = cdi;
ddlIndex.DataTextField = "Content";
ddlIndex.DataBind();
}
catch (SqlException exi)
{
Response.Write(exi.Message.ToString());
}
finally
{
cni.Close();
}
}
}

No comments:

Post a Comment