我真的很喜欢编码 我有一个用计时器刷新的树视图。 如何确保每次刷新时都会突出显示所选节点
感谢任何帮助 感谢
以下是我的代码:
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");
}
}
答案 0 :(得分:2)
假设o.Key
是一个字符串,并且每个字符串都是唯一的并且在buckets.S3Objects
中最多出现一次,请尝试在重新填充TreeView
之前保存所选值,然后再次选择它之后。
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);
}
上述几种方法,例如Select
,Cast
和SingleOrDefault
,都是LINQ的一部分。
答案 1 :(得分:0)
假设这是您正在讨论的ASP.NET(不是ASP.NET MVC),您可以在Page_Load()
事件处理程序中执行此操作。请务必检查IsPostBack == true
例如,
private void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// set selected node here
}
}
如果您使用的是ASP.NET MVC,则只需将该属性存储在ViewBag中。