Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have sql table 1 that contains itemcode - itemcount - tablename
and my windows form1 contains listview1 and button1

what i'm trying to do is that when i click on button1 all listview1 SubItems[1] values in the column to update from tables names in SubItems[2] values where itemcode values are SubItems[0]


i tried the following code but it did what it should do but for the first row only not the rest:

C#
foreach (ListViewItem item in listView1.Items)
{
item.Selected = true;
}

if (cn.State == ConnectionState.Closed) cn.Open();

cm = new SqlCommand();

cm.Connection = cn;

ListViewItem lvi1 = listView1.SelectedItems[0];

string tableName = lvi1.SubItems[2].Text;

string itemcode1 = lvi1.SubItems[0].Text;

string itemcode2 = lvi1.SubItems[1].Text;

string sql = "UPDATE " + tableName + " SET [itemcount]= " + itemcode2 + " WHERE [itemcode]= " + itemcode1 + " AND [itemcount] IS NOT NULL";

cm.CommandText = sql;

cm.ExecuteNonQuery();

Posted
Updated 17-Oct-15 20:47pm
v2
Comments
Michael_Davies 18-Oct-15 2:46am    
Why set the listview items as selected, just use the loop to execute the updates.

Have you set MultiSelect = true for your listview, if not only one item can be selected and selecting an item deselects the current selected item.
Ahmed Zoeil 18-Oct-15 3:10am    
thanks Michael_Davies for your reply

can modify my code and show me how to make the loop in code ?

i'm stuck for 2 days and will appreciate your help
Michael_Davies 18-Oct-15 3:12am    
Making sure the listview has multiselect=true will make your code work as it stands.
Ahmed Zoeil 18-Oct-15 3:17am    
can I minus the values in itemcount in listview1 from the values in the tables before update and update itemcode with the result ?
Ahmed Zoeil 18-Oct-15 3:19am    
and by the way .. multiselect is already set to true

1 solution

I would recommend you use SQL parameter instead of building an SQL string but...As requested:

C#
if (cn.State == ConnectionState.Closed) cn.Open();
 
cm = new SqlCommand();
 
cm.Connection = cn;

foreach (ListViewItem item in listView1.Items)
{
   string sql = "UPDATE " + item.SubItems[2].Text + " SET [itemcount]= " + item.SubItems[1].Text + " WHERE [itemcode]= " + item.SubItems[0].Text + " AND [itemcount] IS NOT NULL";
 
   cm.CommandText = sql;
   cm.ExecuteNonQuery();
} 
 
Share this answer
 
Comments
Ahmed Zoeil 18-Oct-15 5:30am    
thank u so so much Michael_Davies ... u made my day
Ahmed Zoeil 18-Oct-15 13:35pm    
@Michael_Davies

may I ask what is the difference between doing it like this or using SQL parameters and can u show me how to do it using SQL parameters plz

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900