Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more: , +
C#
protected void imgbtnSave_Click(object sender, ImageClickEventArgs e)
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["dbConnection"].ToString());
        con.Open();

        for (int i = 0; i < ddlTesterName.Items.Count && i < ddlBuildNO.Items.Count && i < lbAddedItems.Items.Count; i++)
        {
          
            
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = "usp_InsertWorkAllocation";
            com = new SqlCommand(str, con);
           

            com.Parameters.AddWithValue("@LID", ddlTesterName.Items[i].ToString());
            com.Parameters.AddWithValue("@BID", ddlBuildNO.Items[i].ToString());
            com.Parameters.AddWithValue("@TID", lbAddedItems.Items[i].ToString());
            com.ExecuteNonQuery();
            com = new SqlCommand(str, con);
            com.ExecuteNonQuery();




        }
    }
Posted
Updated 11-Feb-12 1:42am
v4
Comments
RDBurmon 11-Feb-12 5:49am    
How many control you have in your ASP page and what are those ?
ythisbug 11-Feb-12 5:54am    
name(label)[dropdownlist(ddlTesterName)]
BuildNo(label)[dropdownlist(ddlBuildNo)]
lbTestCase(as listbox)lbAddedItems(as Listbox)
from lbTestCase m adding list to lbAddedItems.
and one button..when i click button it should add in sql selected dropdowns values and selected multiple list items from lbAddedItems..

any question??
Tech Code Freak 11-Feb-12 6:20am    
How do you want these entries inserted in the database?
If you want to select multiple items from the listbox, then those items will be saved in one cell in the database, or as different entries?
eg:
Id TesterName BuildNo AddedItems
1 Alex 1 abc,xyz,pqr
2 Roger 2 mno,def
3 Sarah 3 ghi,wxy

OR

Id TesterName BuildNo AddedItems
1 Alex 1 abc
2 Alex 1 xyz
3 Alex 1 pqr
4 Roger 2 mno
5 Roger 2 def
6 Sarah 3 ghi
7 Sarah 3 wxy

Select the way you want the entries to be inserted and I will guide you further.
ythisbug 11-Feb-12 7:15am    
second one

Id TesterName BuildNo AddedItems
1 Alex 1 abc
2 Alex 1 xyz
3 Alex 1 pqr
4 Roger 2 mno
5 Roger 2 def
6 Sarah 3 ghi
7 Sarah 3 wxy
Tech Code Freak 11-Feb-12 8:48am    
Now checkout my ready to use solution--Solution 3
Add click on Accept Solution for all working Solutions.
Don't forget to vote!

Not like that. Rule number one when working with databases, USE PARAMETERIZED QUERIES!!! I can't say this too many times, and yet I already have.
First of all, parameterized queries make for better performance. Sql server caches your queries and by parameterizing them the chance of a query being re-used, and thus using cache instead of doing the entire query again, raises significantly.
But, I year you say "my computer is fast enough I don't care if I get my data in 10 or 15 milliseconds". Well, you might be right, so there is another VERY IMPORTANT REASON to parameterize your queries: SQL INJECTION[^]! I don't know how your drop down box is filled, but let's say a user can enter dropdown values somewhere. The user enters "D'Artagnan", do you see what happens? The ' will break your query and your user will get an exception instead of expected results! In worst case scenario's hackers will get user information, login names, unencrypted passwords etc. or delete entire tables and databases! "Wow", I hear you think, "that's pretty serious, what do I have to do!?".
Well, luckily, parameterizing your queries isn't to difficult. Here's what to do:
C#
// Replace this code:
str = "insert into tblWorkAllocation values('" + ddlTesterName.Items[i].ToString() + "','" + ddlBuildNO.Items[i].ToString() + "','" + lbAddedItems.Items[i].ToString() + "')";
com = new SqlCommand(str, con);
com.ExecuteNonQuery();

// With this code:
str = "insert into tblWorkAllocation values('@TesterName','@BuildNO','@AddedItem')";
com = new SqlCommand(str, con);
com.Parameters.AddWithValue("@TesterName", ddlTesterName.Items[i].ToString());
com.Parameters.AddWithValue("@BuildNO", ddlBuildNO.Items[i].ToString());
com.Parameters.AddWithValue("@AddedItem", ddlAddedItems.Items[i].ToString());
com.ExecuteNonQuery();
As you can see your code is cleaner and more readable. No more nasty string concatenation. But the biggest importance here is that your parameters (@TesterName, @BuildNO, @AddedItem) are now replaced with the values you added to the parameter collection of your Command Object. "D'Artagnan" will now be accepted as a proper value, sql injection has become an impossibility or at least really very unlikely and you and your users can breathe easy knowing that your code is correct and safe!

As for your question:
I think this line of code is stopping the loop from ever looping more than once:
C#
if (ddlTesterName.Items[i].Selected == true && ddlBuildNO.Items[i].Selected == true && lbAddedItems.Items[i].Selected ==true)
Since only one item can be selected at one time :)
Hope this helps!
 
Share this answer
 
v2
Comments
thatraja 11-Feb-12 6:11am    
Spot on & Excellent. 5!
Sander Rossel 11-Feb-12 6:17am    
Thanks thatraja :)
ythisbug 11-Feb-12 6:57am    
thanks naerling.bt m getting errors...1)Error The best overloaded method match for 'System.Data.SqlClient.SqlParameterCollection.AddWithValue(string, object)' has some invalid arguments
Argument '2': cannot convert from 'method group' to 'object'
Sander Rossel 11-Feb-12 7:20am    
Show me your code. Use "improve question" in the lower right corner of your original question.
ythisbug 11-Feb-12 7:33am    
i updated..check it out..
You can build up a single command containing multiple row information:

SQL
INSERT INTO "table_name" ("column1", "column2", ...) VALUES ("value1", "value2", ...) ("next value1", "next value2", ...)
I would use a StringBuilder rather than a string for this.

Unfortunately, AFAIK (and I would love to be told different) you can't do multiple inserts using parametrized queries, which you should really be using to avoid SQL Injection attacks.

[edit]
There is a way to do this, without building a command string, and using parametrized queries, and issuing just the single update: BulkUpdate from a DataTable:
C#
string strConnect = @"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlBulkCopy bulk = new SqlBulkCopy(con))
        {
        bulk.DestinationTableName = "Test";
        DataTable dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Columns.Add("Data");
        dt.Rows.Add("ID 1", "DATA 1");
        dt.Rows.Add("ID 2", "DATA 2");
        dt.Rows.Add("ID 3", "DATA 3");
        dt.Rows.Add("ID 4", "DATA 4");
        bulk.WriteToServer(dt);
        }
    }
All you have to do is create three columns, each with the name of your DB column, then add each row as you go round your loop.
[/edit]
 
Share this answer
 
v2
Comments
Espen Harlinn 11-Feb-12 7:26am    
Parameter names has to be unique - new parameter names for each row ...
OriginalGriff 11-Feb-12 7:52am    
Yes, I thought so. I know you can do this with a BulkInsert via DataTable, but I thought that was a bit heavy duty for something like this.
On seconds thoughts...
Espen Harlinn 11-Feb-12 7:59am    
I would love to be told different ...
While possible, the thing would be somewhat unwieldly - just think about what will happen if OP changes his stored procedure and adds a parameter or two ...
Sander Rossel 11-Feb-12 8:28am    
Never used SqlBulkCopy myself, interesting thought though. My 5 for a good suggestion.
Tech Code Freak 11-Feb-12 8:51am    
5up!
Use the following code:
Create your connection and open it, then add the following:
[EDIT]
First, run a query:
SQL
Select top 1 WID from tblWorkAllocation order by WID desc

This will give you the last entered WID(primary key). Store it in a variable
C#
int wid=0;
object obj=SqlCommand1.ExecuteScalar();
if(obj!=null)
   wid=Convert.ToInt32(obj.ToString());

using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
    bulk.DestinationTableName = "Test";
    DataTable dt = new DataTable();
    dt.Columns.Add("WID");
    dt.Columns.Add("LID");
    dt.Columns.Add("BID");
    dt.Columns.Add("TID"); 
    for(int i=0; i<lbAddedItems.Items.Count; i++)
    {
        if(lbAddedItems.Items[i].Selected)
        {   dt.Rows.Add(++wid, ddlTesterName.SelectedItem.ToString(), ddlBuildNO.SelectedItem.ToString(), lbAddedItems.Items[i].ToString());
        }
    }
    bulk.WriteToServer(dt);
}
[/EDIT]
 
Share this answer
 
v7
Comments
Espen Harlinn 11-Feb-12 10:18am    
5'ed!
Tech Code Freak 12-Feb-12 0:36am    
Thanks!
ythisbug 12-Feb-12 23:29pm    
WID(pk) LID BID TID

643 10.2.3 test3 NULL
644 10.2.3 test8 NULL
645 10.2.3 test10 NULL
hi brother its adding like this..
ythisbug 12-Feb-12 23:33pm    
in lid column shuld add Tesrername ,BID column shuld add build no and TID column should add Testcases..can any one tel what s the error..??
Tech Code Freak 13-Feb-12 0:29am    
For the primary key, you must first retrieve the last entered WID in the table. then increment it in the loop. And then enter in the database. I am updating my Solution further as per your requirement.
3rd solution..and thanks guys ur logic also working..
C#
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["dbConnection"].ToString());
        con.Open();
         for (int i = 0; i < ddlTesterName.Items.Count && i < ddlBuildNO.Items.Count && i < lbAddedItems.Items.Count; i++)
        {
            com = new SqlCommand(str, con);
          
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = "usp_InsertWorkAllocation";
                     
            SqlParameter pLID = new SqlParameter("@LID", SqlDbType.VarChar, 50);
            SqlParameter pBID = new SqlParameter("@BID", SqlDbType.VarChar, 50);
            SqlParameter pTID = new SqlParameter("@TID", SqlDbType.VarChar, 50);
 
            //com.Parameters.AddWithValue("@LID", ddlTesterName.Items[i].ToString());
            //com.Parameters.AddWithValue("@BID", ddlBuildNO.Items[i].ToString());
            //com.Parameters.AddWithValue("@TID", lbAddedItems.Items[i].ToString());

            com.Parameters.AddWithValue("@LID",ddlTesterName.SelectedItem.ToString());
            com.Parameters.AddWithValue("@BID",ddlBuildNO.SelectedItem.ToString());
            com.Parameters.AddWithValue("@TID",lbAddedItems.Items[i].ToString());
            com.ExecuteNonQuery();
        }
 
Share this answer
 
v2
Comments
Anuja Pawar Indore 29-Feb-12 4:27am    
Added code block
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["dbConnection"].ToString());
con.Open();

for (int i = 0; i < ddlTesterName.Items.Count && i < ddlBuildNO.Items.Count && i < lbAddedItems.Items.Count; i++)
{
com = new SqlCommand(str, con);

com.CommandType = CommandType.StoredProcedure;
com.CommandText = "usp_InsertWorkAllocation";


SqlParameter pLID = new SqlParameter("@LID", SqlDbType.VarChar, 50);
SqlParameter pBID = new SqlParameter("@BID", SqlDbType.VarChar, 50);
SqlParameter pTID = new SqlParameter("@TID", SqlDbType.VarChar, 50);

//com.Parameters.AddWithValue("@LID", ddlTesterName.Items[i].ToString());
//com.Parameters.AddWithValue("@BID", ddlBuildNO.Items[i].ToString());
//com.Parameters.AddWithValue("@TID", lbAddedItems.Items[i].ToString());
 
com.Parameters.AddWithValue("@LID",ddlTesterName.SelectedItem.ToString());
com.Parameters.AddWithValue("@BID",ddlBuildNO.SelectedItem.ToString());
com.Parameters.AddWithValue("@TID",lbAddedItems.Items[i].ToString());
com.ExecuteNonQuery();
 
Share this answer
 

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