0

我正在尝试在更新一些数据后更新 gridview。这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = University.GetConnectionString();
    con.Open();
    string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
    SqlCommand cmd = new SqlCommand(query, con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    studentLevel.DataSource = dt;
    studentLevel.DataBind();
    con.Close();
}
protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int row = -1;
    int.TryParse(e.CommandArgument as string, out row);

    GridViewRow gdrow = studentLevel.Rows[row];
    DataRow dr = ((DataTable)studentLevel.DataSource).Rows[gdrow.DataItemIndex];

    string id = dr["ID"].ToString();
    Student student = new Student(Convert.ToInt32(id), "", "", "", "", "", "", "");
    if (e.CommandName == "Undergraduate")
        student.setLevelRole(new UnderGraduateStudent());
    else if (e.CommandName == "Graduate")
        student.setLevelRole(new GraduateStudent());
    student.writeLevelRole(id);

    SqlConnection con = new SqlConnection();     //HERE IS DUPLICATION
                                                 //refresh the gridview on the page
    con.ConnectionString = University.GetConnectionString();
    con.Open();
    string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
    SqlCommand cmd = new SqlCommand(query, con);  
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    studentLevel.DataSource = dt;
    studentLevel.DataBind();
    con.Close();
}

问题是,如果我不写代码的最后 12 行,这与 page_load 方法的代码相同,gridview 不会在页面上自行刷新。我能做些什么来避免这种情况?

谢谢

4

1 回答 1

1

您应该提供一个加载数据和数据绑定的方法GridView,例如DataBindGrid

private void DataBindGrid()
{
    using(var con = new SqlConnection(University.GetConnectionString()))
    {
        con.Open();
        string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
        SqlCommand cmd = new SqlCommand(query, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        studentLevel.DataSource = dt;
        studentLevel.DataBind();
    }
}

然后你可以从任何你需要的地方调用它。如果你想改变一些东西,你只需要维护一个不易出错的地方。

if(!IsPostBack)请注意,只有在使用ViewState(默认)时才应该对 GridView 进行数据绑定:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostback))
        DataBindGridView();
}

并且在RowCommand

protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
   // ... update student ... then
   DataBindGridView();
}
于 2013-06-09T22:02:54.040 回答