I’m trying to populate a Gridview with results from loop. But I’m getting only last result in the loop.
I think GridView is being overwritten on every time the for loop is being executed.
Can you people help me to remove this problem please.
for (int j = 0; j < i; j++)
{
Label1.Text += fipath[j];
Label1.Text += "-------------";
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='" + NAME + "' AND FilePath='" + fipath[j] + "'", conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (Role.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
rdr.Close();
}
catch
{
conn.Close();
}
}
There is more than one problem with this code:
Role== "admin"you don’t need to query db at allDataSourceof the grid is overridden on every loop iteration, this is why you see only the last value.SqlCommandto prevent SQL injection.StringBuilderinsteadusingfor your connection. The code is cleaner this way.The fix could look like this:
Also, I don’t know how many elements your normal loop is. If it is one or two and you have appropriate indexes in
FileUploadtable then it is ok to leave as is. However, if you need to do the for many times you should consider switching to a single query insteadFor example:
This query is SQL injection prone. And has a 2100 elements limit in MS SQL.
There is more than one way to approach this. Depends on your DBMS and requirements.