2014-02-15 58 views
0

試圖將三個文本框插入到gridview的頭文件中,並用按鈕在數據庫中執行「INSERT INTO」。InsertCommand進入頭文件模板

在我的在線服務器數據庫中:idt是int,datetime是varchar,而col1,col2,col3是數字。

<asp:SqlDataSource 
    id="SqlDataSource1" 
    ConnectionString="<%$ ConnectionStrings:connone %>" 
    SelectCommand="SELECT * FROM [test];" 
    InsertCommand="INSERT INTO [test] [datetime],[col1],[col2],[col3] VALUES @datetime,@col1,@col2,@col3;" 
    runat="server"> 
    <InsertParameters> 
     <asp:Parameter Name="datetime" Type="String" /> 
     <asp:Parameter Name="col1" Type="Double" /> 
     <asp:Parameter Name="col2" Type="Double" /> 
     <asp:Parameter Name="col3" Type="Double" /> 
    </InsertParameters> 
</asp:SqlDataSource> 

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 
    SqlDataSource1.InsertParameters("@datetime").DefaultValue = DateTime.Now.ToString() 
    SqlDataSource1.InsertParameters("@col1").DefaultValue = CType(GridView1.HeaderRow.FindControl("TextBoxHeadercol1"), TextBox).Text 
    SqlDataSource1.InsertParameters("@col2").DefaultValue = CType(GridView1.HeaderRow.FindControl("TextBoxHeadercol2"), TextBox).Text 
    SqlDataSource1.InsertParameters("@col3").DefaultValue = CType(GridView1.HeaderRow.FindControl("TextBoxHeadercol3"), TextBox).Text 
    SqlDataSource1.Insert() 
End Sub 

<asp:GridView ID="GridView1" 
    runat="server" 
    DataSourceID="SqlDataSource1" 
    AutoGenerateColumns="False" 
    DataKeyNames="idt"> 
    <Columns> 
     <asp:BoundField DataField="idt" HeaderText="idt" Readonly="true" SortExpression="idt" /> 
     <asp:BoundField DataField="datetime" HeaderText="datetime" SortExpression="datetime" /> 
     <asp:TemplateField SortExpression="col1"> 
      <HeaderTemplate> 
       <asp:TextBox ID="TextBoxHeadercol1" text="col1" runat="server" MaxLength="40" /> 
      </HeaderTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField SortExpression="col2"> 
      <HeaderTemplate> 
       <asp:TextBox ID="TextBoxHeadercol2" text="col2" runat="server" MaxLength="40" /> 
      </HeaderTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField SortExpression="col3"> 
      <HeaderTemplate> 
       <asp:TextBox ID="TextBoxHeadercol3" text="col3" runat="server" MaxLength="40" /> 
      </HeaderTemplate> 
     </asp:TemplateField> 
</asp:GridView> 

回答

0

我建議刪除 「@」 在InsertParameters如下:

SqlDataSource1.InsertParameters("col1").DefaultValue =  
    ((TextBox)GridView1.HeaderRow.FindControl("TextBoxHeadercol1")).Text; 

這應該工作。