我有一個列表框,它將字典中的id添加到列表框中,但我需要它顯示名稱而不是id,但該項目的值必須是id辦法做到這一點繼承人的代碼我使用更改列表框中的文本而不更改值
public static Dictionary<int, CardInfos> CardDataeff = new Dictionary<int, CardInfos>();
private void textBox2_TextChanged(object sender, EventArgs e)
{
lock (Searchlock)
{
if (textBox2.Text == "")
{
listBox2.Items.Clear();
return;
}
if (textBox2.Text != "Search")
{
listBox2.Items.Clear();
foreach (int card in CardDataeff.Keys)
{
if (CardDataeff[card].Id.ToString().ToLower().StartsWith(textBox2.Text.ToLower()) ||
CardDataeff[card].Name.ToLower().Contains(textBox2.Text.ToLower()))
{
listBox2.Items.Add(CardDataeff[card].Id.ToString());
}
}
}
}
}
public void listBox2_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
int index = e.Index;
if (index >= 0 && index < listBox2.Items.Count)
{
string text = listBox2.Items[index].ToString();
Graphics g = e.Graphics;
CardInfos card = CardDataeff[Int32.Parse(text)];
g.FillRectangle((selected) ? new SolidBrush(Color.Blue) : new SolidBrush(Color.White), e.Bounds);
// Print text
g.DrawString((card.Name == "" ? card.Id.ToString() : card.Name), e.Font, (selected) ? Brushes.White : Brushes.Black,
listBox2.GetItemRectangle(index).Location);
}
e.DrawFocusRectangle();
}
private bool LoadCard(int cardid)
{
if (!CardDataeff.ContainsKey(cardid))
{
return false;
}
CardInfos info = CardDataeff[cardid];
if (!string.IsNullOrEmpty(this.richTextBox1.Text))
{
if (MessageBox.Show("do you want to save? ", "Prompt", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
{
if (string.IsNullOrEmpty(this.filePath))
{
this.saveFileDialog1.InitialDirectory = this.scriptFolderPath;
this.saveFileDialog1.FileName = this.getFileName();
if (this.saveFileDialog1.ShowDialog() != DialogResult.OK)
this.saveFile(this.saveFileDialog1.FileName);
}
else
{
this.saveFile(this.filePath);
}
}
}
this.openFile(cdbdir + "\\script\\c" + cardid + ".lua");
return true;
}
private void listBox2_DoubleClick(object sender, EventArgs e)
{
ListBox list = (ListBox)sender;
if (list.SelectedIndex >= 0)
{
LoadCard(Int32.Parse(list.SelectedItem.ToString()));
}
}
我包括我認爲是必要的所有代碼
由於某種原因,我的意見與的werent你的代碼的工作,我得到這個錯誤錯誤「System.Windows.Forms.ListView」不包含'SelectedItem'的定義,並且沒有找到接受類型'System.Windows.Forms.ListView'的第一個參數的擴展方法'SelectedItem'(可以找到缺少使用指令或程序集引用嗎?) – outlaw1994
nvm修復了錯誤通過這樣做int id =(int)listView1.SelectedItems [0] .Tag; – outlaw1994
對不起,這是我的錯誤我編輯我的代碼 –