Callum
Callum

Reputation: 3381

Foreach loop help c#

I'm currently trying to pull data from a database using a variable and then pass it into a foreach loop to determine if a button should be shown based on a value.

SO far I have this:

var Inter = from x in db.DT_Interviews where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID select x;

foreach(var c in Inter)
{
    if (c.InterviewDone == true)
        BTI.Visible = false;
    else
        BTI.Visible = true;
 }

However I am unable to get the loop to work! Can someone show me or explain what I am doing wrong here?

Upvotes: 0

Views: 210

Answers (3)

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

Firstly, why have you got a foreach to set 2 scenarios only i.e. set the visibility of some object to false or true. Imagine if your Inter has got 5 bool values, then the visibility of your object is dependant upon the last value in the Inter because it will continue to loop until it hits the last value. Isn't it. Try this code:

Here, I am getting a bool value in Inter as soon as it finds the first value.

var Inter = (from x in db.DT_Interviews
             where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID
             select x.InterviewDone).FirstOrDefault();

if(Inter)
{
    BTI.Visible = false;
}      
else
{
    BTI.Visible = true;
}

Upvotes: 0

vc 74
vc 74

Reputation: 38179

If you're trying to show BTI if any interview is associated to the viewstate client ID and having the InterviewDone flag = true, you can use:

int clientID = int.Parse(ViewState["ClientID"].ToString());
BTI.Visible = db.DT_Interviews.Any(x => x.ClientID == clientID && x.InterviewDone);

But why do you need to check that the ClientID is same as the one in the view state AND CID?

Upvotes: 1

Alexander Galkin
Alexander Galkin

Reputation: 12524

Your code is very strange at several places:

var Inter = 
  from x in db.DT_Interviews 
  where x.ClientID == int.Parse(ViewState["ClientID"].ToString()) && x.ClientID == CID 
  select x; 

Are you sure that your query returns any result? what is the value of CID?

  foreach(var c in Inter) 
  { 
     if (c.InterviewDone == true) 
            BTI.Visible = false; 
         else 
            BTI.Visible = true; 
      } 
  }

I am not sure that you are doing here? The BTI will be visible or not depeding upon the last element in your query. So, why to loop over the whole content then?

Upvotes: 0

Related Questions