2014-02-13 77 views
0

我想通過在C#語句「.Insert()」中使用asp:SqlDataSource InsertCommand來執行「INSERT INTO」命令。在Gridview中插入命令

按鈕「btninsert」駐留在gridview的標題字段中,就像插入Textboxes:「TextBoxHeadercol1」,「TextBoxHeadercol2」和「TextBoxHeadercol3」一樣。

我有4列在我的表中,「測試」,他們是「idt」,「col1」,「col2」,「col3」。我的Gridview是「gvtotal」。

我知道col1,col2和col3將不打印數據,因爲我將ItemTemplate與標籤區分開來。

public void btninsert_Click(object sender, EventArgs e) 
    { 
     SqlDataSource1.InsertParameters["col1"].DefaultValue = ((TextBox)gvtotal.HeaderRow.FindControl("TextBoxHeadercol1")).Text; 
     SqlDataSource1.InsertParameters["col2"].DefaultValue = ((TextBox)gvtotal.HeaderRow.FindControl("TextBoxHeadercol2")).Text; 
     SqlDataSource1.InsertParameters["col3"].DefaultValue = ((TextBox)gvtotal.HeaderRow.FindControl("TextBoxHeadercol3")).Text; 
     SqlDataSource1.Insert(); 
    } 
<asp:GridView ID="gvtotal" 
    runat="server" 
    DataSourceID="SqlDataSource1" 
    AutoGenerateColumns="False" 
    DataKeyNames="idt"> 
    <Columns> 
     <asp:BoundField DataField="idt" HeaderText="idt" Readonly="true" SortExpression="idt" /> 
     <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:TemplateField> 
      <HeaderTemplate> 
       <asp:Button ID="btninsert" runat="server" Text="Insert Into" OnClick="btninsert_Click" /> 
      </HeaderTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 
<asp:SqlDataSource 
    id="SqlDataSource1" 
    ConnectionString="<%$ ConnectionStrings:connone %>" 
    SelectCommand="SELECT * FROM [test];" 
    InsertCommand="INSERT INTO [test] [col1],[col2],[col3] VALUES @col1,@col2,@col3;" 
    runat="server" 
/> 

回答

0

我想你可能會通過使用由SQLDataSource提供的InsertCommand模板逃脫這一點。寫這個命令的SqlDataSource爲

的InsertCommand =「INSERT INTO測試(......)VALUES(@ VAL1,@值2,@ VAL3)

使用的SqlDataSource模板映射@ VAL1,@ VAL2和@ VAL3文本盒子你想要的。所提供的快速模板將有助於這一點。在對插入的單擊事件,只需刷新網格視圖以顯示新的內容

public void btninsert_Click(object sender, EventArgs e) 
{ 
    gridview.DataBind(); 
} 

請注意,我沒有Visul Studio中我的機器上。假設上述代碼爲僞代碼