Reputation: 195
I have a webform wherein the admin will add new records to database. The form has 1 dropdownbox drpDepartments
and a few textboxes EmployeeID, Fname, Lname
, etc. I can add a new record but the option chosen from the dropdownbox isn't changing. It's always the first value. Here are tables tblEmployee
and tblDepartment
.
Here's my Page_Load()
code:
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
dsEmp = new DataSet();
dsDep = new DataSet();
daEmp.Fill(dsEmp, "tblEmployee");
daDep.Fill(dsDep, "tblDepartment");
dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DataTextField = "Description";
drpDepartments.DataValueField = "DeptID";
drpDepartments.DataBind();
And the btnAdd_Click()
code:
cb = new SqlCommandBuilder(daEmp);
DataRow dRow = dsEmp.Tables["tblEmployee"].NewRow();
dRow["EmployeeID"] = txtID.Text;
dRow["Lname"] = txtLname.Text;
dRow["Fname"] = txtFname.Text;
dRow["Mname"] = txtMname.Text;
dRow["Address"] = txtAddress.Text;
dRow["Email"] = txtEmail.Text;
dRow["Phone"] = Convert.ToInt64(txtPhone.Text);
dRow["Jobtitle"] = txtJobtitle.Text;
dRow["Salary"] = txtSalary.Text;
dRow["DeptID"] = drpDepartments.SelectedValue;
dsEmp.Tables["tblEmployee"].Rows.Add(dRow);
daEmp.Update(dsEmp, "tblEmployee");
dsEmp.Tables["tblEmployee"].AcceptChanges();
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test", "<script>alert('New record added!');</script>");
Refresh();
Upvotes: 0
Views: 55
Reputation: 4864
The binding of dropdown must be only in !IsPostBack
if(!IsPostBack)
{
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
drpDepartments.DataBind();
}
If you bind the DropDownList in postback event, the dropdown will be re-binded in the the button_click (in the page_load) event and the value set by the user will be lost.
Upvotes: 3