我有一个datagrid,我已经填充了来自sql数据库的数据。我还添加了一个功能,可以将新联系人添加到数据库,效果很好。我遇到的问题是,添加联系人并点击F5(刷新网页)后,它会向数据库添加另一个相同的联系人。ASP.NET避免在页面刷新中添加新数据
我在回发后清除textfields,但不知何故字符串留在内存中,每次刷新网页时都会添加另一个联系人。
我也有问题的DataGrid没有立即更新后点击按钮,这就是为什么我必须更新页面的第一个地方。我相信这两个问题可能有关。
这里是我的代码背后,我不认为aspx页面将是必要的,但如果需要我可以给它。
public partial class Default : System.Web.UI.Page
{
SqlConnection connection = new SqlConnection("server = Sqlconnection; uid = username; pwd = password; database = database;");
protected void Page_Init(object sender, EventArgs e)
{
//------------------------------------------------DataGrid--------------------------------------------------
SqlDataAdapter SqlCommandDG = new SqlDataAdapter("SELECT FirstName, LastName, Email, PhoneNumber, CompanyName FROM ContactPerson CP, Company C WHERE CP.[CompanyID] = C.[Company_ID]", connection);
DataSet ds = new DataSet();
SqlCommandDG.Fill(ds);
DataView source = new DataView(ds.Tables[0]);
DataGrid1.DataSource = source;
DataGrid1.DataBind();
//----------------------------------------------Dropdown list------------------------------------------------
SqlCommand SqlCommandDD = new SqlCommand("SELECT * FROM Company");
SqlCommandDD.Connection = connection;
connection.Open();
DropDownList1.DataSource = SqlCommandDD.ExecuteReader();
DropDownList1.DataValueField = "Company_ID";
DropDownList1.DataTextField = "CompanyName";
DropDownList1.DataBind();
connection.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
connection.Open();
string fName = fNameTextBox.Text;
string lName = lNameTextBox.Text;
string email = EmailTextBox.Text;
string phoneNr = phoneNrTextBox.Text;
string company = DropDownList1.SelectedValue;
string sqlquery = ("INSERT INTO ContactPerson (FirstName, LastName, Email, PhoneNumber, CompanyID) VALUES ('" + fNameTextBox.Text + "','" + lNameTextBox.Text + "','" + EmailTextBox.Text + "','" + phoneNrTextBox.Text + "','" + DropDownList1.SelectedValue + "')");
SqlCommand command = new SqlCommand(sqlquery, connection);
command.Parameters.AddWithValue("FirstName", fName);
command.Parameters.AddWithValue("LastName", lName);
command.Parameters.AddWithValue("Email", email);
command.Parameters.AddWithValue("PhoneNumber", phoneNr);
command.Parameters.AddWithValue("CompanyID", company);
command.ExecuteNonQuery();
fNameTextBox.Text = string.Empty;
lNameTextBox.Text = string.Empty;
EmailTextBox.Text = string.Empty;
phoneNrTextBox.Text = string.Empty;
connection.Close();
}
}
我怎么会检查,而不必经过我的数据库中的所有recods的存在?我试图没有任何成功的SQL查询中的IF NOT EXISTS行。另外,我将如何创建BindGrid()方法并将其绑定到我的数据网格? – Joel 2012-03-19 14:35:42
@Mynter:我将如何创建BindGrid()方法? - 根据Kaf的回答,“从Page_Init方法中删除数据绑定代码并创建一个名为”BindGrid()“的相同代码的新方法。 – Chris 2012-03-19 15:39:38
**如何创建:** private void BindGrid(){//剪切并粘贴Page_Init()方法中的所有代码}'您已经将网格绑定在上面的代码中。你可以用'IF NOT EXIST'位发布你的查询吗? – Kaf 2012-03-19 16:15:49