Question

I'm really new to coding I have a treeview that refreshes with a timer. How can i make sure i keep my selected node highlighted every time it refreshes

Appreciate any help Thanks

Here is the code that I have:

    private void PopulateTree(ListObjectsResponse buckets)
    {
        treeView1.Nodes.Clear();
        List<TreeItem> items = new List<TreeItem>();
        foreach (S3Object obj in buckets.S3Objects)
        {
            treeView1.Nodes.Add(new TreeNode(obj.Key));
        }
    }

    private void button4_Click_1(object sender, EventArgs e)
    {
        timer1.Enabled = true;
        existingBucketName = label3.Text + "-DP";
        AmazonS3Client client = new AmazonS3Client();
        ListObjectsRequest listRequest = new ListObjectsRequest
        {
            BucketName = existingBucketName,
        };

        try
        {
            ListObjectsResponse listResponse;
            listResponse = client.ListObjects(listRequest);
            PopulateTree(listResponse);
        }
        catch
        {
            timer1.Enabled = false;
            MessageBox.Show("There is no folder for this user");
        }
    }
Was it helpful?

Solution

Assuming that o.Key is a string, and that each string is unique and occurs at most once in buckets.S3Objects, try saving the selected value before repopulating the TreeView, then select it again afterwards.

private void PopulateTree(ListObjectsResponse buckets)
{
    // Since you're about to clear out all current TreeNode instances, storing a
    // reference to SelectedNode is not enough. You're setting o.Key as the Text
    // for each TreeNode, so save the selected node's Text value. 
    var selectedText
        = treeView1.SelectedNode == null ? "" : treeView1.SelectedNode.Text;

    // Repopulate your TreeView with new TreeNodes
    treeView1.Nodes.Clear();
    treeView1.Nodes.AddRange(buckets.S3Objects.Select(o => new TreeNode(o.Key)).ToArray())

    // Look for the TreeNode with the same Text that you had selected before.
    // If it's not found, then SelectedNode will be set to null
    treeView1.SelectedNode =
        = treeView1.Nodes.Cast<TreeNode>()
                         .SingleOrDefault(n => n.Text == selectedText);
}

Several of the above methods, such as Select, Cast, and SingleOrDefault, are part of LINQ.

OTHER TIPS

Assuming this is ASP.NET (not ASP.NET MVC) that you're talking about, you would do this in the Page_Load() event handler. Be sure to check whether IsPostBack == true

For example,

private void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    // set selected node here
  }
}

If you are using ASP.NET MVC then just store the property in the ViewBag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top