我创建了2个DropDownLists第一个下拉列表包含" TeamName"第二个包含" TeamMember"名称。要求是当我们从下拉列表中选择特定的TeamName时,第二个下拉列表应该自动填充团队成员名称,并且在按钮点击数据应该插入数据库之后,它适用于第一次按钮点击但第二次在同一页面上#34; TeamName&# 34;下拉列表没有显示部门名称,突然之间就丢失了。所以请告诉我需要做些什么才能解决这个问题?
以下是我为完成此任务所做的代码
User.aspx page code:
User.aspx.cs页面代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTeamName();
txtCurrentDate.Text = DateTime.Now.ToString("MM-dd-yyyy");
txtCurrentDate.ForeColor = System.Drawing.Color.Green;
}
}
private void BindTeamName()
{
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamName", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl1.DataSource = ds;
ddl1.DataTextField = "TeamName";
ddl1.DataValueField = "TeamId";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
int TeamId = Convert.ToInt32(ddl1.SelectedValue);
SqlConnection con = new SqlConnection(SqlString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from TeamResource where TeamId=" + TeamId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl2.DataSource = ds;
ddl2.DataTextField = "EmpName";
ddl2.DataValueField = "EmpId";
ddl2.DataBind();
ddl2.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (SqlConnection con = new SqlConnection(SqlString))
{
SqlCommand cmd = new SqlCommand("InsertUserData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@WorkDate", txtCurrentDate.Text);
cmd.Parameters.AddWithValue("@TeamName", ddl1.SelectedItem.Text);
cmd.Parameters.AddWithValue("@TeamMember", ddl2.SelectedItem.Text);
cmd.Parameters.AddWithValue("@AvailableBandwidth", ddlAvailable.SelectedItem.Value);
con.Open();
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
}
}
答案 0 :(得分:0)
我会重新绑定" TeamName"成功保存后的下拉列表。
//btnSubmit_Click
if (ReturnCode == -1)
{
lblMsg.Text = "Already Data present";
lblMsg.ForeColor = System.Drawing.Color.Red;
ClearFields();
}
else
{
lblMsg.Text = "Data inserted successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
ClearFields();
BindTeamName(); //re-bind the initial dropdown so you can select a new team
}
实际上,您可以使用该方法,具体取决于ClearFields()
的作用。