3

我有一个gridview定义为

 <asp:UpdatePanel ID="up2" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="Click" />
    </Triggers>
    <ContentTemplate>
        <asp:GridView ID="GridView1" DataSourceID="employee" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" DataKeyNames="id" AllowPaging="true" AllowSorting="true" runat="server" CellPadding="4" ForeColor="#333333" 
            GridLines="None">
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
      </asp:GridView>   
      <asp:SqlDataSource ID="employee" runat="server" ConnectionString="values go here" SelectCommand="select * from employee" UpdateCommand="update employee set name=@name, company=@company, salary=@salary where id=@id" DeleteCommand="delete from employee where id=@id"></asp:SqlDataSource>        
    </ContentTemplate>
 </asp:UpdatePanel>

每次单击提交按钮时,我都需要更新它。提交按钮定义为

 protected void btnSubmit_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnection xconn = new SqlConnection();
        xconn.ConnectionString = @"values go here";
        xconn.Open();
        string str = "insert into employee(name, company, salary) values(@name, @company, @salary)";
        SqlCommand ycmd = new SqlCommand(str, xconn);
        ycmd.Parameters.Add("@name", txtname.Text);
        ycmd.Parameters.Add("@salary", txtsalary.Text);
        ycmd.Parameters.Add("@company", txtcompany.Text);
        ycmd.ExecuteNonQuery();
        lblresult.Text = "Record successfully inserted";            
    }
    catch (SqlException e1)
    {
        lblresult.Text = "<span style='color:red;'>" + e1.Message + "<br />" + e1.StackTrace + "</span>";
    }
    catch (Exception e2)
    {
        lblresult.Text = "<span style='color:red;'>" + e2.Message + "<br />" + e2.StackTrace + "</span>";
    }
    finally
    {
        txtname.Text = "";
        txtcompany.Text = "";
        txtsalary.Text = "";
    }
}

但是,网格不会更新btnSubmit_Click

有什么解决方案?

4

1 回答 1

2

你需要

GridView1.DataBind();

强制网格重新查询数据。

于 2013-01-06T20:06:01.360 回答