【发布时间】:2012-04-04 00:20:39
【问题描述】:
我有一个数据网格,其中填充了来自 sql 数据库的数据。我还添加了一项功能,可以将新联系人添加到数据库中,效果很好。我遇到的问题是,在添加联系人并点击 F5(刷新网页)后,它会将另一个相同的联系人添加到数据库中。
我在回发后清除文本字段,但不知何故,字符串留在内存中,并在每次刷新网页时添加另一个联系人。
我还遇到了点击按钮后数据网格没有立即更新的问题,这就是我必须首先更新页面的原因。我相信这两个问题可能是相关的。
这是我的代码,我认为 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();
}
}
【问题讨论】:
标签: asp.net .net sql database datagrid