Sunday, October 9, 2011

How to Insert data into Database Tables Using DropDownList and Sql Command


In this Tutorial we can easily code that how we can make our dropdownlist data available to SQL Server Database. Firstly we have to go through aspx page code that is users input page.

default.aspx page code:
This is user's input page or presentation page.
 <b>City:&nbsp;</b>&nbsp;&nbsp;  
     <asp:DropDownList ID="DropDownList1" runat="server"  
       Height="20px" style="margin-left: 0px" Width="128px">  
       <asp:ListItem>Rudrapur</asp:ListItem>  
       <asp:ListItem>Delhi</asp:ListItem>  
       <asp:ListItem>Mumbai</asp:ListItem>  
     </asp:DropDownList>  
     <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />  

default.aspx.cs page code:
This is button click event, on click of Button1 on user's input page (aspx page) selected option from dropdownlist will be inserted in sql server database using the following code. Here we are inserting city's value in column city of table1 in Database.mdf 
 protected void Button1_Click(object sender, EventArgs e)  
   {  
  using (SqlConnection sqlcon = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"))  
     {  
    SqlCommand CmdSql = new SqlCommand("INSERT INTO [Table1] (City) VALUES (@City)", sqlcon);  
    sqlcon.Open();  
    CmdSql.Parameters.AddWithValue("@City", DropDownList1.SelectedValue);  
    CmdSql.ExecuteNonQuery();  
    sqlcon.Close();  
     }  
   }  

No comments:

Popular Posts