何を作っているかぐらいは書きましょうよ。TextBox, ListBox というのは、Windows Forms, WPF, ASP.NET Web Forms のいずれにもあります。すでに、Windows Forms という前提で回答が出ていますが、実は質問者さんが作っているのは WPF, ASP.NET Web Forms だったとすると、回答者の方が回答に費やした労力と時間を無駄にしたことになりますよ。
Idの値を登録するテキストボックス(textBox1)に入力したIdの値が既にリストボックス(listBox1)に存在していた場合、リストボックスのAgeの値のみ更新するという感じのコードを書きたいのですがどう組み立てれば良いのでしょうか?
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
回答1件
0
ベストアンサー
Dictionary を使ってやってみました。
C#
1using System; 2using System.Collections.Generic; 3using System.Windows.Forms; 4 5namespace WindowsFormsApplication1 6{ 7 public partial class Form1 : Form 8 { 9 private class Person 10 { 11 public string ID; 12 public int Age; 13 public int Index; 14 15 public override string ToString() 16 { 17 return ID + ":" + Age.ToString(); 18 } 19 }; 20 21 private Dictionary<string, Person> _list; 22 23 public Form1() 24 { 25 InitializeComponent(); 26 } 27 28 private void Form1_Load(object sender, EventArgs e) 29 { 30 _list = new Dictionary<string, Person>(); 31 } 32 33 private void button1_Click(object sender, EventArgs e) 34 { 35 int age = 0; 36 if (int.TryParse(textBox2.Text, out age)) 37 { 38 if (_list.ContainsKey(textBox1.Text)) 39 { 40 Person p = _list[textBox1.Text]; 41 p.Age = age; 42 // Refresh() 等では更新されなかったので、セットしなおし。 43 //listBox1.Refresh(); 44 //listBox1.Invalidate(); 45 //listBox1.Update(); 46 listBox1.Items[p.Index] = p; 47 } 48 else 49 { 50 Person p = new Person(); 51 p.ID = textBox1.Text; 52 p.Age = age; 53 p.Index = listBox1.Items.Count; 54 _list[p.ID] = p; 55 listBox1.Items.Add(p); 56 } 57 } 58 } 59 } 60} 61 62
投稿2019/04/02 18:40
総合スコア108
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。