Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello, how can I use varible from for each in another place?
my code:
string jobtitle;
if (st2 != null)
            {
                foreach (var item in st2)
                {
                    var prop = item.UserJobTitle;
                    jobtitle = Convert.ToString(prop);
                }
            }

st2 is itemsource from virtual DataGrid
in this foreach i just have a data and i dont need use a list, and i want use my varible(jobtitle) in my textbox,

What I have tried:

i tried everyway i guess,but did't worked ... :(
Posted
Updated 9-Nov-23 0:52am
v2
Comments
CHill60 9-Nov-23 7:02am    
Your question is not clear. If you assign the text of a textbox with jobtitle it will be overwritten with each st2 in the list
Richard MacCutchan 9-Nov-23 9:18am    
You just need to decide which of the elements in the list you want to save, and stop the loop at that point. As it stands jobtitle will always contain the value of the last item.
Dave Kreskowiak 9-Nov-23 9:22am    
It's not clear what you are trying to do with this code. "User this variable in another place" is not that goal. What are you trying to do with the data in st2? (bad variable name by the way)
PIEBALDconsult 9-Nov-23 10:12am    
I doubt you need to use the Convert class; please don't. Try using a cast instead. You also don't need the local variable prop.
Do you want to maybe fill a List<string> with the values?

Your question is very unclear...

Using your code and keeping in mind that the 'jobtitle' will change with every iteration of your loop, you can try the following, which will only show the last record in the loop -

C#
//Using a TextBox named textBoxJobTitle in your form...
string jobtitle = ""; 
//Make sure to initialize your variable

if (st2 != null)
{
    foreach (var item in st2)
    {
        var prop = item.UserJobTitle;
        jobtitle = Convert.ToString(prop);
    }
}

//Now use the jobtitle value into your TextBox text
textBoxJobTitle.Text = jobtitle;
 
Share this answer
 
Your code iterating through the items in st2 (collection of objects) and extract the UserJobTitle property from each item. If you only need the last UserJobTitle in the loop and want to use it in another place (like a TextBox), then refer to the Solution-2.
If you want to set the value in another place (like a TextBox) upon a condition then you can modify your code as:
C#
if (st2 != null)
{
	foreach (var item in st2)
	{
		// Your condition to check the job title, here you can use a string constant or enum
		if(Convert.ToString(item.UserJobTitle) == "AnyJobTitle")
		{
			textBoxJobTitle.Text = Convert.ToString(item.UserJobTitle);
		}
	}
}
 
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