Click here to Skip to main content
15,920,678 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to insert contents of the listbox into my database. the code am using is shown below. it doesnt seem to work. kindly help me out

for (i = 0; i <= addedroles.Items.Count; i++)
     {
      sql = "insert into roles(dept_id, role) values('" + id + "', '" + addedroles.Items[i] + "')";
     
      SqlCommand insert = new SqlCommand(sql, conn);
      cmd.ExecuteNonQuery();
      }
Posted

What about setting a breakpoint at
SqlCommand insert = new SqlCommand(sql, conn);


and try to execute the sql statement in sql management studio?

It will hopefully tell you something about what's going wrong ...

Hiren is also on to something - you probably want check that the element type has a ToString() override returning the required text, or cast to the element type and access the correct property directly.

Regards
Espen Harlinn
 
Share this answer
 
v2
Comments
Dalek Dave 17-Jan-11 10:40am    
Good Call
Espen Harlinn 17-Jan-11 10:59am    
Thanks Dalek!
You seem to have to created an SqlCommand called 'insert', but then called 'cmd.ExecuteNonQuery()' to try and get the command to work.

However in the code snippet you've provided, 'cmd' doesn't exist.

Maybe try calling 'insert.ExecuteNonQuery()' instead?
 
Share this answer
 
Comments
Dalek Dave 17-Jan-11 10:40am    
Well spotted.
Try it by foreach loop, Like

C#
foreach (ListItem item in lb.Items)
        {
            string Text = item.Text;
            string Value = item.Value;
        }


And prepare your query accordingly. And let us know if you're facing any error regarding.
 
Share this answer
 
Comments
[no name] 17-Jan-11 8:45am    
do i need to declare the ListItem name?
Manfred Rudolf Bihy 19-Jan-11 16:18pm    
Wow got an accepted answer voted down! I had that happen to me before also and thought to myself WTF! 5+

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