我正在尝试通过复选框和其他值存储列表视图表中记录的ID号,并且在我单击“提交”按钮后出现此错误。它说有一个空值。
以下是填充表格:
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = @"SELECT EmployeeID, FirstName, LastName, Position FROM
Employees ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
这是提交点击代码:
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmpPart");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = @"INSERT INTO CourseParticipants VALUES (@TrainingModuleID, @EmployeeID, @Active, @DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("@EmployeeID", 1);
cmd.Parameters.AddWithValue("@Active", 1);
cmd.Parameters.AddWithValue("@DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
//con.Close();
}
}
}
}
}
}
这是.aspx
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td>
<asp:CheckBox ID="cbEmployee" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
答案 0 :(得分:3)
首先将DataKeyNames
添加到aspx页面上的ListView。
<asp:ListView ID="lvEmployees" runat="server" DataKeyNames="EmployeeID">