2011-11-21 151 views
0

我試圖插入數據到SQL Server 2000數據庫,但徒勞無功。我正在使用Visual Studio 2010.我正在使用下面的代碼,當我單擊要插入的按鈕時不會生成任何錯誤,而是將NULL作爲表中的字符串插入到兩列中。請幫忙或者告訴我如何編寫一個簡單的應用程序,將一些數據插入到數據庫表中。感謝你們。插入數據到SQL Server數據庫

下面是我迄今成功地編寫和正在使用的SQL數據源代碼:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 
    <h2> 
     My Test Insert 
    </h2> 
    <p class="style1"> 
     <asp:TextBox ID="FirstName" runat="server" Width="258px"></asp:TextBox> 
    </p> 
     <p class="style1"> 
     <asp:TextBox ID="LastName" runat="server" style="text-align: center" 
      Width="260px"></asp:TextBox> 
    </p> 
    <p class="style1"> 
     <asp:Button ID="Button1" runat="server" Text="Button" Width="89px" /> 
    </p> 
<p class="style1"> 
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
    </p> 
    <p class="style1"> 
     <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
      ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
      InsertCommand="INSERT INTO TblNames(FirstName, LastName) VALUES (@FirstName, @LastName)" 
      SelectCommand="SELECT * FROM [TblNames]"> 
      <InsertParameters> 
       <asp:Parameter Name="FirstName" /> 
       <asp:Parameter Name="LastName" /> 
      </InsertParameters> 

     </asp:SqlDataSource> 
    </p> 

    </asp:Content> 

按鈕點擊事件:

Partial Class _Default 
    Inherits System.Web.UI.Page 

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 
     'If the page is valid, add the new product 
     If Page.IsValid Then 
      SqlDataSource1.Insert() 

      'Display confirmation message 
      Label1.Text = String.Format("Name {0} has been added to the database...", FirstName.Text) 
     End If 
    End Sub 
End Class 
+3

你有什麼錯誤,如果有的話? –

+0

你的問題是什麼? –

+0

嗨我沒有得到任何錯誤的代碼執行時,我點擊按鈕和警報成功觸發,足夠有趣,如果我檢查表我可以看到NULL插入在這兩欄好心幫助或給我另一種代碼,我可以嘗試。謝謝 –

回答

0

你有沒有嘗試過的button1_Click不

If Page.IsValid Then 

+0

是的,我已經嘗試沒有如果page.IsValid但仍然插入NULL到數據庫表。 –

0

從MSDN庫,您的InsertParameters

<InsertParameters> 
    <asp:FormParameter Name="FirstName" FormField="FirstName" /> 
    <asp:FormParameter Name="LastName" FormField="LastName" /> 
</InsertParameters> 

在這段代碼中,你是在告訴Insert參數的名稱和值將是什麼。 此外,還有<asp:ControlParameter>的選項,它還允許您指定參數的名稱和controlid,它將爲您提供參數的值。

+0

我也試過這個,但我看到NULL插入表加班我點擊按鈕。請幫助 –