使用asp.net中的更新面板更新按钮上的gridview

时间:2013-01-06 20:03:01

标签: c# asp.net ado.net

我将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

上更新

这是什么解决方案?

1 个答案:

答案 0 :(得分:2)

你需要

GridView1.DataBind();

强制网格重新查询数据。