C#のlistについての質問です。
質問を投稿するのも初めてなので、至らない点が多々あると思いますがよろしくお願いします。
Windows 10 の Visual Studio 2022 で Windows Forms アプリをターゲットフレームワーク .NET Framework 4.8 で作っています
SQL Server のバージョン・エディションは、2022でlocalDBで作っております
SQL Severから取得した値をフィールドのListに格納し、
WindowsFormApplicationのclass Form1のlistboxに表示するようなシステム
を考えております。
質問事項:
SQL Severから取得した値をフィールドのListに格納できても、
(☆class1.Select();での処理ではうまく格納できている)
★への処理に移ると、データがリセットしてしまいます。
(ID.Countが0になるため、データを表示できない)
どうしたら☆class1.Select();での処理したフィールド変数の値を保持したまま
★の処理に移行できますか。
以下コード:
class Form1 //フィールド変数の定義 public string abc = "{0,-10}{1,-20}"; private List<string> id { get; set; } = new List<string>(); public List<string> ID { get => id; set => id=value; } private List<string> country { get; set; } = new List<string>(); public List<string> Country { get => country; set => country=value;} private void Form1_Load(object sender, EventArgs e) { listBox1.Items.Add(string.Format(abc, "id", "country")); ☆// SQL Serverからデータの抽出処理 Class1 class1 = new Class1(); class1.Select(); ★//Form1のlistboxに追加 for (int i = 0; i < ID.Count; i++) { listBox1.Items.Add(string.Format(abc, id[i], country[i])); } } class Class1 internal class Class1:Form1 { public void Select() { //SQL Serverに接続処理 //抽出処理 cmd.CommandText = "SELECT * FROM Countrys"; SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string aa = dr["country_id"].ToString(); string bb = dr["country"].ToString(); //フィールド変数に格納 this.ID.Add(aa); this.Country.Add(bb); } SQL Serverに接続切断処理 }
回答2件
あなたの回答
tips
プレビュー