如何从列表框中的对象中选择值
本文关键字:对象 选择 列表 | 更新日期: 2023-09-27 18:36:59
Here is the list item Class:
class ListItem
{
public string Key;
public string Value;
public ListItem()
{
}
public string key
{
get { return Key; }
set { key = value; }
}
public string value
{
get { return Value; }
set { Value = value; }
}
public override string ToString()
{
return Key;
}
public string getvalue(string blabla)
{
return Value;
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
string[] Folders = Directory.GetDirectories(txtFolder.Text);
foreach (string f in Folders)
{
ListItem n = new ListItem();
n.Value = f;
n.Key = Path.GetFileName(f);
listBoxSidra.Items.Add(n);
}
}
private void listBoxSidra_SelectedIndexChanged_1(object sender, EventArgs e)
{
try
{
lblmsg.Text = null;
comboBoxSeason.Items.Clear();
string[] seasons = Directory.GetDirectories(listBoxSidra.SelectedValue.ToString());
for (int i = 0; i < seasons.Length; i++)
{
comboBoxSeason.Items.Add(seasons[i]);
}
comboBoxSeason.SelectedIndex = 0;
}
catch (Exception ex)
{
lblmsg.Text = ex.Message;
}
}
第一种方法:我打开名为ListItem
的类,它包含文件夹名称(键)和文件夹位置(值)。Secound方法:我创建了一个数组,其中包含我在文本框上设置的目录中的所有子目录。我还创建了ListItem
名为"n"的对象,然后将值设置为"n",n.Value(表示目录位置)和n.Key(表示目录名称)。下一步是将"n"对象添加到列表框中,现在在列表框中我可以看到目录名称,每个对象都包含他的位置。
Thrid 方法:这就是 im 卡住的地方,我创建了一个数组,该数组假设包含所选列表框项中的子目录,我的意思是,当我单击列表框项时,我想获取他的值(值代表位置),然后通过将子目录添加到数组中,我应该写什么而不是listBoxSidra.SelectedValue.ToString()
?
谢谢!
为了使您的代码正常工作,请进行以下更改
private void btnOpen_Click(object sender, EventArgs e)
{
string[] Folders = Directory.GetDirectories(txtFolder.Text);
var dataSource = new List<ListItem>();
foreach (string f in Folders)
{
ListItem n = new ListItem();
n.Value = f;
n.Key = Path.GetFileName(f);
dataSource.Add(n);
}
listBoxSidra.DataSource = dataSource;
listBoxSidra.DisplayMember = "key";
listBoxSidra.ValueMember = "value";
}