C# と WinForms で ListBox に項目を追加する
    
    Muhammad Zeeshan
    2024年2月15日
    
    Csharp
    Csharp WinForms
    
 
ListBox コントロールは、WinForms でいくつかの項目をリストに表示するために使用されます。ユーザーはそこから 1つまたは複数の要素を選択できます。多くの場合、コンポーネントは複数の列に表示されます。 このチュートリアルでは、C# と WinForms を使用して ListBox にアイテムを追加する方法について説明します。
ListBox に項目を追加するメソッド
    
方法 1 - WinForms でのドラッグ アンド ドロップ
WinForms の ListBox に項目を追加するには、次の手順に従います。
- 
Visual Studioで新しいWindows Formsプロジェクトを作成し、意味のある名前を付けます
- 
次に、ToolBoxの左側のパネルからListBoxを検索します 
- 
Windows フォームにドラッグ アンド ドロップします。
- 
ListBoxに新しいアイテムを追加するには、ListBoxを右クリックします。
- 
プロパティで、Itemsを見つけて 3つのドットをクリックし、項目を追加してOKをクリックします。 
- 
最後に、windows-form を実行します
出力:

方法 2 - C# でコードを記述して、ListBox に項目を手動で追加する
    
コードを記述して、ListBox に項目を手動で追加できます。 この概念をよりよく理解するために、例を見てみましょう。
- 
まず、次のライブラリをインポートしますusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;
- 
shaniListという名前のListBoxリストを作成しますListBox shaniList = new ListBox();
- 
次に、以下に示すように、アイテムをリストに追加しますshaniList.Items.Add("Cut"); shaniList.Items.Add("Paste"); shaniList.Items.Add("Copy");
- 
最後のステップとして、Controls.Add()によってListBoxコントロールをフォームに追加します。this.Controls.Add(shaniList);
完全なソース コード:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddItemtoListBoxbyZeeshan {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e) {
      ListBox shaniList = new ListBox();
      shaniList.Location = new Point(150, 70);
      shaniList.Items.Add("Cut");
      shaniList.Items.Add("Paste");
      shaniList.Items.Add("Copy");
      this.Controls.Add(shaniList);
    }
  }
}
出力:

        チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
    
著者: Muhammad Zeeshan
    I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.
LinkedIn