我有一個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