Add and show items using dropdownlist

Satyapriyanayak
Posted by Satyapriyanayak under ASP.NET category on | Points: 40 | Views : 878
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Dropdownlist_Insertshow._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Name" Width="100px"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="btn_add" runat="server" Text="Add Name" onclick="btn_add_Click"
Width="100px" /><br />
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList><br />

</div>
</form>
</body>
</html>



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace Dropdownlist_Insertshow
{
public partial class _Default : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dropbind();
}
}

protected void btn_add_Click(object sender, EventArgs e)
{
DropDownList1.Items.Clear();
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "Insert into employee values('" + TextBox1.Text + "')";
com = new SqlCommand(str, con);
com.ExecuteNonQuery();
Response.Write("Records successfully inserted");
clear();
dropbind();
}
private void clear()
{
TextBox1.Text = "";
}
private void dropbind()
{

SqlConnection con = new SqlConnection(strConnString);
DropDownList1.Items.Add("Choose Name");
con.Open();
str = "select * from employee";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
DropDownList1.Items.Add(reader["name"].ToString());
}
reader.Close();
con.Close();
}

}
}

Comments or Responses

Login to post response