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.
     <asp:DropDownList ID="DropDownList1" runat="server"  
       Height="20px" style="margin-left: 0px" Width="128px">  
     <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);  
    CmdSql.Parameters.AddWithValue("@City", DropDownList1.SelectedValue);  

No comments:

Popular Posts