Abdur Razique

Abdur Razique

  • NA
  • 124
  • 1.4k

Loop inside loop C#

Aug 3 2017 3:03 PM
Hi i am having a problem writing C# code for my Web application.
 
I have an MS SQL Table named "Table_xyz" with two columns "User_id" & "Refrence_ID"
 
 User_id Reference_id
 1 0
 2 1
 3
 4 3
 5 4
 
I just only want to retrieve all "User_id" based on it's "Refrence_ID" in a loop
 
My Command: Select User_id from Table_xyz where Reference_ID = '0' (This is only to start the loop)
 
The loop must start referencing only from the reference_id which i will enter(it may be any reference id from the table)
 
According to the above command the result will give "1" which is the parent "User_id", for the "Reference_ID" '0'
 
But the issue comes here, i want to keep this first result to retrieve the next result for second result and then for third and so on.
 
Means the result(returned value) will become the "Reference_ID" for upcoming query looping each other and this way it will find entire table.
 
My Code below:
 
try
{
nCon.Open();
var gCmd = new SqlCommand(@"SELECT User_id FROM Table_xyz WHERE Reference_id = '0'", nCon);
SqlDataAdapter Sda = new SqlDataAdapter(gCmd);
DataTable Dt = new DataTable();
Sda.Fill(Dt);
int i = 0;
do
{
if (i < Dt.Rows.Count)
{
Response.Write(Dt.Rows[i]["User_iD"]);
i++;
}
}
while (i < Dt.Rows.Count);
}
catch (Exception e) { Response.Write(e.Message); }
finally { nCon.Close(); }

Answers (2)