简体   繁体   English

在asp.net C#中插入后如何刷新GridView

[英]How to refresh gridview after insertion in asp.net c#

I am using gridview in a page of website that I am builing with asp.net so I am using sqldatasource component to fill gridview.now I insert new data into the table and page is refreshed but new data is not displayed in the gridview how to solve this problem 我在用asp.net构建的网站页面中使用gridview,所以我使用sqldatasource组件填充gridview.now,我将新数据插入表中并刷新页面,但新数据未显示在gridview中解决这个问题

见图片

Bind your gridview again after inserting new data. 插入新数据后再次绑定gridview。 It will take time but you have to fetch the data from database and bind it again to gridview. 这将花费一些时间,但是您必须从数据库中获取数据并将其再次绑定到gridview。

Gridview.DataSource = yourDataSource;
Gridview.DataBind();

Bind the Grid in page_Init() 在page_Init()中绑定网格

It bind the data from your database Every page init 它将绑定数据库中的数据绑定到每个页面init

Documentation on inserting using SqlDataSource - SqlDataSource.Insert Method() 有关使用SqlDataSource进行插入的文档-SqlDataSource.Insert Method()

And here's a complete, wroking example: 这是一个完整的,令人费解的示例:

Code behind: 后面的代码:

public partial class SqlDataSourceExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnInsert_Click(object sender, EventArgs e)
    {
        SqlDataSource1.Insert();
    }
}

.ASPX: .ASPX:

<form id="form1" runat="server">
    <asp:SqlDataSource 
        ID="SqlDataSource1" 
        runat="server" 
        ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" 
        SelectCommand="SELECT [ID], [Name], [Surname] FROM [Person]"
        InsertCommand="INSERT INTO [Person](Name,Surname)VALUES(@name,@surname)">
        <InsertParameters>
            <asp:ControlParameter ControlID="txtName" Name="name" />
            <asp:ControlParameter ControlID="txtSurname" Name="surname" />
        </InsertParameters>
    </asp:SqlDataSource>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Surname" HeaderText="Surname" SortExpression="Surname" />
        </Columns>
    </asp:GridView>
    <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
    <asp:Label ID="lblSurname" runat="server" Text="Surname"></asp:Label>
    <asp:TextBox ID="txtSurname" runat="server"></asp:TextBox><br />
    <asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" />
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM