Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,
I've a query to which i need to pass the id in loop,(i.e., for(int i=0;i<45;i++)
after every iteration i need that retrieved data in dataSet. so that i can view that all data after the loop.
ex:
C#
for (int i = 0; i < 45; i++)
{
    string str = " SELECT * from Table1 where id='"+i+"'";


    SqlCommandcmd = new SqlCommand(str, conn);

    SqlDataAdapter adp = new SqlDataAdapter(cmd);

    DataTable dt = new DataTable();
    adp.Fill(dt);

    gridview1.DataSource = dt;
    gridview1.DataBind();
}
Posted
Updated 19-Nov-14 3:26am
v2
Comments
Richard Deeming 19-Nov-14 11:01am    
NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Although this particular case isn't vulnerable to SQL Injection[^], as you're passing an int, you should still get into the habit of using parameterized queries for everything.

Doing it that way will get you only one ID at a time.

If you are using SQL Server, you can use a Table-Valued Parameter.
Use your for loop to fill a DataTable with the IDs, then pass them as a parameter to the query.

SQL Server 2008 User Defined Table Types and Table-Valued Parameters[^]
 
Share this answer
 
Comments
sumangta 19-Nov-14 9:56am    
okay... thanks for the suggestion.
and by the end i need those values for every ID which i passed individually
to be filled in Dataset (i.e all the entries for every ID's)
is it possible.
You can achieve this with single call of database. Review below block of code. I make two small change and this will give proper result with less time.


C#
string strIds = string.Empty;

for (int i = 0; i &lt; 45; i++)
{
	strIds = strIds == string.Empty ? "'" + i.ToString() + "'" : (",'" + i.ToString() + "'");
}

string str = " SELECT * from Table1 where id IN (" + strIds + ")";

SqlCommandcmd = new SqlCommand(str, conn);

SqlDataAdapter adp = new SqlDataAdapter(cmd);

DataTable dt = new DataTable();
adp.Fill(dt);

gridview1.DataSource = dt;
gridview1.DataBind();
 
Share this answer
 
Comments
Richard Deeming 19-Nov-14 11:01am    
NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

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