在表格頂部
Dictionary<string, string> FileList = new Dictionary<string, string>();
在建構式中
public Form1()
{
InitializeComponent();
if (System.IO.File.Exists(Path.Combine(path, "test.txt")))
{
string g = System.IO.File.ReadAllText(Path.Combine(path, "test.txt"));
FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
listBox1.DataSource = FileList.ToList();
}
而是制作:
listBox1.DataSource = FileList.ToList();
然后在串列框中我會看到例如“hello”、“d:\test\test1.txt”
我希望在串列框中只有:“你好”
我不想更改 FileList,而是更改將從 FileList 添加到 listBox 的內容,而這只是左側。
另一個問題可能是 listBox selected index :
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = ((ListBox)sender).SelectedItem;
var itemCast = (KeyValuePair<string, string>)item;
pictureBox1.Image = System.Drawing.Image.FromFile(itemCast.Value);
}
一方面,我不想在右側的 listBox 中看到值,另一方面,我希望選定的索引事件能夠正常作業。
uj5u.com熱心網友回復:
字典將鍵映射到值。您所說的“左側/側面”實際上是鍵,另一個元素是值。
C#Dictionary有一個屬性:Keys它只回傳字典中的鍵"hello"(例如你的字串)。
因此,您可以使用:
listBox1.DataSource = FileList.Keys.ToList();
請注意,如果您只需要值(例如"d:\test\test1.txt"等),Dictionary則具有類似的屬性:Values.
uj5u.com熱心網友回復:
我猜,當用戶選擇一個鍵時,你會想要得到相應的值。在這種情況下,不僅系結鍵,還系結整個Dictionary:
myListBox.DisplayMember = "Key"
myListBox.ValueMember = "Value"
myListBox.DataSource = myDictionary.ToArray()
每個專案都是一個KeyValuePair,它具有Key和Value屬性。上面的代碼將顯示鍵,然后,當用戶選擇一個專案時,您可以從SelectedValue屬性中獲取相應的值。
請注意,像這樣的資料系結需要一個IList,而Dictionary唯一的實作ICollection。因此,您需要呼叫ToArray或ToList創建一個IListfor 系結。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516756.html
標籤:C#表格
上一篇:如何更改工具提示文本的字體大小?
