I have a listbox that contains column "RoleName" values for a specific user (specified by my label5). However, when I try to delete multiple selected records, or 1 selected record, nothing gets deleted. I think it has to do with my data binding.
Error:
No mapping exists from object type System.Data.DataRowView to a known managed provider native type.
Code:
private void btnDelete_Click(object sender, EventArgs e)
{
con.Open();
for( int x = 0; x <listBox1.SelectedItems.Count - 1 ; x++)
{
SqlCommand cmd = new SqlCommand("DELETE FROM Josh_REL_Table where UserID = @UserID and RoleName = @RoleName", con);
cmd.Parameters.AddWithValue("@UserID", label5.Text);
cmd.Parameters.AddWithValue("@RoleName", listBox1.SelectedValue);
cmd.ExecuteNonQuery(); //error
}
}
I try going through the list of items that I selected, set my parameters, then execute the query. Or maybe my SelectedValue or SelectedItem is wrong?
My other approach was to create a list, populate that list with my RoleName values, then insert the list values into my listbox to hopefully avoid databinding limitations, if that's the issue. However my listbox doesn't get populated.
Code:
private void Form1_Load(object sender, EventArgs e)
{
List<string> RoleList = new List<string>();
con.Open();
SqlCommand com = new SqlCommand();
com.CommandText = "Select RoleName from Josh_Rel_Table where UserID = '" + label5.Text + "'";
IDataReader reader = com.ExecuteReader();
{
while (reader.Read())
{
RoleList.Add(reader.GetString(0));
listBox1.Items.Add(reader.GetString(0));
}
reader.Close();
}
}
Which approach is better and any advise on a solution to my problem? Thanks.
Aucun commentaire:
Enregistrer un commentaire