2015-04-05 78 views
1

表單按鈕:值插入SQL Server的使用asp.net

<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" /> 

後面的代碼:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
End Sub 
  1. 什麼是簡單的代碼插入值(生成的ID)爲SQL服務器數據庫當觸發Button1_Click時,應將生成的ID插入到tbl_batch

  2. 我應該添加任何東西到web.config(如db連接)?

回答

1
Using con As SqlConnection = New SqlConnection("Server=localhost\SQLEXPRESS; Database=databasename; User Id=sa; Password=yourpassword;") 
      Using cmd As SqlCommand = con.CreateCommand() 
       Using da As New SqlDataAdapter 
        con.Open() 

        cmd.CommandText = "insert into ..." 
        da.SelectCommand = cmd 
        Dim dt As New DataTable 
        da.Fill(dt) 

       End Using 
      End Using 
     End Using 
1

您不能在web.config文件中執行CRUD操作,但我有一個使用SqlDataSource的簡單解決方案。按照以下步驟進行操作,並以簡單的方式讓你的事情發生。

連接字符串中我的web.config:

<add name="Conn" connectionString="Server=David-PC;Database=DNN711;uid=sa;pwd=sa123;" providerName="System.Data.SqlClient"/> 

ASPX標記:

<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" /> 

    <asp:SqlDataSource ID="sdsInsert" runat="server" 
     ConnectionString="<%$ ConnectionStrings:Conn %>" 
     InsertCommand="Insert into tbl_batch (GeneratedID) values (@GeneratedID)" 
     InsertCommandType="Text"></asp:SqlDataSource> 

按鈕單擊事件:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    sdsInsert.InsertParameters.Add("GeneratedID", "123"); 
    sdsInsert.Insert(); 
} 

如果您有任何問題,請讓我知道。