我正在根据项目列表执行销售订单。 我有两个下拉列表。 First下拉列表从Projects表中检索数据。第二个下拉列表是根据第一个下拉列表中的选定值填充数据。
下面显示了项目和任务的下拉列表的源代码。
<!--Project-->
<div class="form-group">
<label class="control-label col-lg-4">
Project</label>
<div class="col-lg-8">
<asp:DropDownList ID="ddlProjects" runat="server" class="form-control"
AutoPostBack="True" DataTextField="Select a project..." DataValueField="AutoId"
onselectedindexchanged="ddlProjects_SelectedIndexChanged" />
</div>
</div>
<!--Tasks-->
<div class="form-group">
<label class="control-label col-lg-4">
Task</label>
<div class="col-lg-8">
<asp:DropDownList ID="ddlTasks" runat="server" class="form-control" />
</div>
</div>
下面显示了下拉列表背后的代码
void GetProjects()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProjectID, Name FROM Projects WHERE Status = 'On Going'";
SqlDataReader dr = cmd.ExecuteReader();
ddlProjects.DataSource = dr;
ddlProjects.DataTextField = "Name";
ddlProjects.DataValueField = "ProjectID";
ddlProjects.DataBind();
con.Close();
}
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
var ID = int.Parse(ddlProjects.SelectedValue);
string sql = "SELECT TaskID, Name FROM ProjectTasks WHERE ProjectID = @ProjectID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Connection = con;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("@ProjectID", ID);
ad.Fill(table);
ddlTasks.DataTextField = "Name";
ddlTasks.DataSource = table;
ddlTasks.DataBind();
}
问题在于每次我打开销售订单表时,默认的DataTextValue都不是我在源代码中声明的那个&#34;选择一个项目&#34;但它显示了第一条记录。
另一件事是我觉得代码仍有问题我无法识别它是什么。
如果您有任何澄清,请告诉我。
答案 0 :(得分:0)
您需要从aspx中删除DataTextField="Select a project..." DataValueField="AutoId"
。您在代码中定义了这一点。
添加您的第一个选项并设置AppendDataBoundItems = true
ddlProjects.Items.Add(new ListItem("Select a project...",""));
ddlProjects.AppendDataBoundItems = true;
ddlProjects.DataSource = dr;
ddlProjects.DataTextField = "Name";
ddlProjects.DataValueField = "ProjectID";
ddlProjects.DataBind();
确保未选择空白项目
protected void ddlProjects_SelectedIndexChanged(object sender, EventArgs e)
{
ddlTasks.Items.Clear();
int ID = 0;
if (int.TryParse(ddlProjects.SelectedValue, out ID))
{
DataTable table = new DataTable();
string sql = "SELECT TaskID, Name FROM ProjectTasks WHERE ProjectID = @ProjectID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Connection = con;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("@ProjectID", ID);
ad.Fill(table);
ddlTasks.DataTextField = "Name";
ddlTasks.DataSource = table;
ddlTasks.DataBind();
}
}