Insert items to database and display it within a dropdownlist after adding in asp.net

Description:-

In this blog we will know how to insert items to database and display it within a dropdown list after adding those items simultaneously.

Create Table:-

CREATE TABLE [dbo].[Food](
[Fid] [bigint] primary key IDENTITY(1,1)NOT NULL,
[Fname] [nvarchar](100)NULL,
[Fprice] [bigint] NULL,
[Recstatus] [char](1)NULL,
)
 
INSERT INTO Food(Fname,Fprice,Recstatus)VALUES('Dal',2000,'A')
INSERT INTO Food(Fname,Fprice,Recstatus)VALUES('Rice',52000,'A')
INSERT INTO Food(Fname,Fprice,Recstatus)VALUES('Tuwerdal',3000,'A')
INSERT INTO Food(Fname,Fprice,Recstatus)VALUES('Chanadal',5000,'A')

Default.aspx:-

<div>
  Name:<asp:TextBox ID="txt_name" runat="server"></asp:TextBox><br />
  Price:<asp:TextBox ID="txt_price" runat="server"></asp:TextBox><br />
  RecStatus:<asp:TextBox ID="txt_recstatus" runat="server"></asp:TextBox><br />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt_name"                 ErrorMessage="Please insert name"></asp:RequiredFieldValidator>
    <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>

Default.aspx.cs:-

string strConnString = ConfigurationManager.ConnectionStrings["DBCS"].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);
  com = new SqlCommand();
  com.Connection = con;
  com.CommandType = CommandType.Text;
  com.CommandText = "INSERT INTO Food(Fname,Fprice,Recstatus)VALUES(@Fname,@Fprice,@Recstatus)";
  com.Parameters.Clear();
  com.Parameters.AddWithValue("@Fname", txt_name.Text);
  com.Parameters.AddWithValue("@Fprice", txt_price.Text);
  com.Parameters.AddWithValue("@Recstatus", txt_recstatus.Text);
  if (con.State == ConnectionState.Closed)
    con.Open();
  com.ExecuteNonQuery();
  con.Close();
  Response.Write("Records successfully inserted");
  clear();
  dropbind();
}

private void clear()
{
  txt_name.Text = "";
}

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

Related Posts

Previous
Next Post »

Thanks for comments.....