I"m developing an application in Microsoft Visual C# 2010.
I"m have a listview where I display the record from database. I want to delete a selected record from listview and of course the same row from database. I found the solution for the first objective but not for the second.
The delete queries don"t want to execute, i can"t figure why!
Oh, and one more thing, I have an error when i want to acces the subitems of the listview, the error sounds like this "invalid argument 0", although i made a test in a Messabox button and gives me the right values of the items.
Please help!
Here is my code:
connect.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Cercetarestiintifica.mdf;Integrated Security=True;User Instance=True";
connect.Open();
foreach (ListViewItem eachItem in lv_profcarte.SelectedItems)
{
lv_profcarte.Items.Remove(eachItem);
}
string cmd1=@"DELETE FROM Profesor WHERE (marca = '"+lv_profcarte.SelectedItems[0].SubItems[3].Text+"')";
string cmd3=@"DELETE FROM Carte WHERE (ISBN = '"+lv_profcarte.SelectedItems[0].SubItems[8].Text+"')";
SqlCommand cmd2 = new SqlCommand(cmd1, connect);
SqlCommand cmd4 = new SqlCommand(cmd3, connect);
cmd2.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
connect.Close();
Dana MariaPosted Mar 29, 2013, 12:44 PM
Jignesh TrivediPosted Mar 29, 2013, 12:00 AM
are you got any error to executing this code?
it might be possible the value of lv_profcarte.SelectedItems[0].SubItems[3].Text is blank or null or containing unwanted space. in sql "Test" is not Equivalent "Test " (value with space).
so suggesting try with trim this value.
string profesor = lv_profcarte.SelectedItems[0].SubItems[3].Text.Trim();
string Carte = lv_profcarte.SelectedItems[0].SubItems[8].Text.Trim();
HOPE THIS WILL RESOLVE YOUR PROBLEM.
Dana MariaPosted Mar 28, 2013, 12:27 PM
Jignesh TrivediPosted Mar 28, 2013, 4:02 AM
hi,
i agree with "Vulpes",
when you access the subitems of the listview, it already remove from list view by your code, so that you can not find Listview1.selectedItems (it is null).
you can also take value from selected item before remove it. use these variables for delete operation.
try...
connect.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Cercetarestiintifica.mdf;Integrated Security=True;User Instance=True";
connect.Open();
string profesor = lv_profcarte.SelectedItems[0].SubItems[3].Text;
string Carte = lv_profcarte.SelectedItems[0].SubItems[8].Text;
foreach (ListViewItem eachItem in lv_profcarte.SelectedItems)
{
lv_profcarte.Items.Remove(eachItem);
}
string cmd1=@"DELETE FROM Profesor WHERE (marca = '"+ profesor +"')";
string cmd3=@"DELETE FROM Carte WHERE (ISBN = '"+ Carte +"')";
SqlCommand cmd2 = new SqlCommand(cmd1, connect);
SqlCommand cmd4 = new SqlCommand(cmd3, connect);
cmd2.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
connect.Close();
hope this will help you.
VulpesPosted Mar 27, 2013, 7:45 PM