我有一个Web表单,其中用户在文本框中输入其雇员ID,单击搜索按钮,然后从搜索结果(单选按钮列表)中选择其姓名。一旦他们选择了自己的名字,一个TabContainer便会出现,其中包含许多标签。每个选项卡面板上都有一个复选框列表,其中列出了他们在完成任务时选择的一系列任务。完成选择项目后,他们单击提交按钮以将记录保存到数据库。选择新选项卡后,将动态创建“复选框列表”和“提交”按钮。 复选框列表正确填充在每个选项卡上,并创建了提交按钮。但是,单击按钮时,事件处理程序不会触发。
要进行故障排除,我将选项卡面板内的按钮硬编码(而不是动态创建提交按钮),并且事件处理程序将触发,但是当尝试将数据发送到数据库时,代码失败,表示“复选框列表”一片空白。我尝试找到“复选框列表”,但未找到。在这里和其他地方阅读了大量类似的问题后,我相信这是因为它在提交时不存在。 单击该按钮时,我需要怎么做才能找到“提交”按钮和“复选框列表”?
这是我的代码:
protected void tabTaskContainer__ActiveTabChanged(object sender, EventArgs e)
{
CheckBoxList cbl = new CheckBoxList();
cbl.ID = "cblCat";
this.tabTaskContainer.ActiveTab.Controls.Add(cbl);
//run query to populate checkboxlist
int category = tabTaskContainer.ActiveTabIndex;
using (MySqlConnection conn = new MySqlConnection())
{
conn.ConnectionString = "connection_string_here";
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "select t2.employee_id, t1.task as 'task',t1.task_id as 'task_id', ifnull(t2.is_complete,0) as 'completed'" +
" from" +
" (select task_id, task" +
" from hot_tasks" +
" where responsibility = 'new-hire'" +
" and category_id = " + category + ") t1" +
" left join" +
" (select employee_id, task_id, is_complete" +
" from completed_hot" +
" where employee_id = @employeeID) t2 on t1.task_id = t2.task_id;";
cmd.Parameters.AddWithValue("@employeeID", Convert.ToInt64(txtEmpID.Text));
cmd.Connection = conn;
conn.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["task"].ToString();
item.Value = sdr["task_id"].ToString();
item.Selected = Convert.ToBoolean(sdr["completed"]);
cbl.Items.Add(item);
}
}
}
conn.Close();
}
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Text = "Submit";
btnSubmit.CausesValidation = false;
btnSubmit.Click += new System.EventHandler(btnSubmit_Click);
tabTaskContainer.ActiveTab.Controls.Add(btnSubmit);
}
以及“提交”按钮的代码:
protected void btnSubmit_Click(object sender, EventArgs e)
{
CheckBoxList cbList = tabTaskContainer.FindControl("cblCat") as CheckBoxList;
if(cbList != null)
{
using (MySqlConnection conn = new MySqlConnection())
{
conn.ConnectionString = "server=connection string here";
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO completed_hot (employee_id, task_id, date_completed, is_complete, empID_taskID) " +
"VALUES(@empid, @taskid, curdate(), @isCompleted, CONCAT(@empID,@taskID)) " +
"ON DUPLICATE KEY UPDATE " +
"date_completed = curdate(), is_complete = @isCompleted;";
cmd.Connection = conn;
conn.Open();
foreach (ListItem item in cbList.Items)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@empID", rblSearchResults.SelectedValue);
cmd.Parameters.AddWithValue("@taskID", item.Value);
cmd.Parameters.AddWithValue("@isCompleted", item.Selected);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
tabTaskContainer.ActiveTab = tabTaskContainer.Tabs[tabTaskContainer.ActiveTabIndex + 1];
}
}