【问题标题】:Insert Command in a Gridview在 Gridview 中插入命令
【发布时间】:2014-03-11 16:59:56
【问题描述】:

我正在尝试通过在 C# 语句“.Insert()”中使用 asp:SqlDataSource InsertCommand 来执行“INSERT INTO”命令。

按钮“btninsert”与插入文本框一样位于网格视图的标题字段中:“TextBoxHeadercol1”、“TextBoxHeadercol2”和“TextBoxHeadercol3”。

我的表中有 4 列“test”,它们是“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"
 />

【问题讨论】:

    标签: asp.net gridview


    【解决方案1】:

    我认为您可以通过使用 SQLDataSource 提供的 InsertCommand 模板来解决这个问题。为 SQLDataSource 编写此命令

    InsertCommand = "INSERT INTO Test(….) VALUES(@val1,@val2,@val3)

    使用 SQLDataSource 模板将@val1、@val2 和@val3 映射到所需的文本框。提供的快速模板将有助于此。在插入的单击事件中,只需刷新网格视图即可显示新内容

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

    请注意,我的机器上没有 Visul Studio。假设上述代码为伪代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 2011-08-07
      • 1970-01-01
      相关资源
      最近更新 更多