1

i'm trying to store the id number of records from the list view table thru check box and other values, and I got this error after i hit the submit button. It says there is a null. enter image description here

Here is the populate the table:

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();
        }
    }
}

Here is the submit click code:

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();

                    }
                }
            }
        }
    }
}

Here is the .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>
VDWWD
  • 35,079
  • 22
  • 62
  • 79
Blurryface213
  • 93
  • 1
  • 10
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/a/4660186/4977870) – Anas Alweish Oct 26 '18 at 12:36

1 Answers1

3

Start by adding the DataKeyNames to the ListView on the aspx page.

<asp:ListView ID="lvEmployees" runat="server" DataKeyNames="EmployeeID">
VDWWD
  • 35,079
  • 22
  • 62
  • 79