I have a JSON file from my local folder:
Shawn Milke.json
{
"FirstName": "Shawn",
"LastName": "Milke",
"Email": "[email protected]",
"TeamName": "Shawn Milke",
"Password": "shawn123",
"IsActive": "Yes",
"UserId": 100
}
Here's the code in populating the listbox from JSON file:
private void ShowListViewNew()
{
List<UserAccount> userAccounts = new List<UserAccount>();
var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var outputDir = Path.Combine(dir, "Output");
foreach (var file in Directory.GetFiles(outputDir, "*.json"))
{
var text = File.ReadAllText(file);
var model = JsonConvert.DeserializeObject<UserAccount>(text);
userAccounts.Add(model);
}
listBoxUsers.DataSource = userAccounts;
}
And here's also my code in populating the textboxes from the listbox selected:
private void listBoxUsers_SelectedIndexChanged(object sender, EventArgs e)
{
var model = (UserAccount)listBoxUsers.SelectedItem;
txtFirstName.Text = model.FirstName;
txtLastName.Text = model.LastName;
txtEmail.Text = model.Email;
txtTeamName.Text = model.TeamName;
txtPassword.Text = model.Password;
if (model.IsActive== "Yes")
{
chkIsActive.Checked = true;
}
else
{
chkIsActive.Checked = false;
}
txtUserId.Text = model.UserId;
}
Now my main problem is I want to know how I can convert it from int to string in this line of code
txtUserId.Text = model.UserId;
Because I usually do it this way:
UserId = int.Parse(txtUserId.Text)
Since now it's changed, I'm not sure on how I can convert it from int to string. Can someone help? Thanks!
CodePudding user response:
There are few ways to do this.
1-) A Simple static method - or you may prefer extension method- can be a proper way of this for the future usings.
public static string ConvertIntToString (int TheInt32)
{
return $"{TheInt32}";
}
Usage:
txtUserId.Text = ConvertIntToString(model.UserId);
2-) Or Simply Convert inline
txtUserId.Text = model.UserId.ToString();
or
txtUserId.Text = "" model.UserId;
or
txtUserId.Text = $"{model.UserId}";
All usage types are valid. As a developer, This will be your choice with depending of which C# version you choosen to use in your project.