Gridview不会在页面加载时更新

时间:2015-03-28 03:39:55

标签: c# gridview ado.net

我有一个gridview没有在pageload上更新。如果在表中插入值,则页面会回发并且gridview保持不变。所有记录都插入到数据库中。我对ADO.NET相当新,任何建议都会非常感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class Equip_DB : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataBind();
        }

        string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            con.Open();
            SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);

            SqlDataReader reads = showAll.ExecuteReader();
            GridView1.DataSource = reads;
            GridView1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
        SqlConnection con = new SqlConnection(cs);
        //INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
        string query = "INSERT INTO Equiptment VALUES ('"+
            equipAmount.Text +"', '"+
            equipType.Text + "', '" +
            DropDownList1.SelectedValue +"')";
        AddContract.Visible = true;
        SqlCommand cmd = new SqlCommand(query, con);
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch {
            con.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您没有使用更新的内容绑定gridview。

  protected void Button1_Click(object sender, EventArgs e)
    {
        string cs = ConfigurationManager.ConnectionStrings["NIC"].ConnectionString;
        SqlConnection con = new SqlConnection(cs);
        //INSERT INTO Equiptment VALUES ('2', 'Hammers', '24')
        string query = "INSERT INTO Equiptment VALUES ('"+
            equipAmount.Text +"', '"+
            equipType.Text + "', '" +
            DropDownList1.SelectedValue +"')";
        AddContract.Visible = true;
        SqlCommand cmd = new SqlCommand(query, con);
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
con.Close();
//GRID LOAD CODE GOES HERE


        using (SqlConnection con = new SqlConnection(cs))
        {
            con.Open();
            SqlCommand showAll = new SqlCommand("SELECT * FROM Equiptment", con);

            SqlDataReader reads = showAll.ExecuteReader();
            GridView1.DataSource = reads;
            GridView1.DataBind();
}

///////////////////////

        }
        catch {
            con.Close();
        }
    }  


        }