尝试存储列表视图ID

时间:2018-10-26 12:32:24

标签: c# sql asp.net

我正在尝试通过复选框和其他值存储列表视图表中记录的ID号,并且在我单击“提交”按钮后出现此错误。它说有一个空值。 enter image description here

以下是填充表格:

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>

1 个答案:

答案 0 :(得分:3)

首先将DataKeyNames添加到a​​spx页面上的ListView。

<asp:ListView ID="lvEmployees" runat="server" DataKeyNames="EmployeeID">