본문 바로가기
개발언어/C#

[C#] listview에 button추가시 샘플1

by 창용이랑 2021. 8. 10.
728x90
        private Button AddBtn;
       
        public Form1()
        {
            InitializeComponent();
            // adds listview to the form
            AddControls();
            // Adding products to the listview
            AddProducts();
        }
        private void AddControls()
        {
            listView1 = new ListView();
            listView1.Location = new System.Drawing.Point(0, 12);
            this.listView1.Name = "listView1";
            this.listView1.Size = new System.Drawing.Size(250, 175);
            this.listView1.TabIndex = 0;
            this.listView1.UseCompatibleStateImageBehavior = false;
            this.listView1.View = System.Windows.Forms.View.Details;

            // Adding listview header
            listView1.Columns.Add("Product name", 100);
            listView1.Columns.Add("Search string", 100);

            this.Controls.Add(listView1);

            // Adds a add button
            this.AddBtn = new System.Windows.Forms.Button();
            this.AddBtn.Location = new System.Drawing.Point(0, 211);
            this.AddBtn.Name = "AddBtn";
            this.AddBtn.Size = new System.Drawing.Size(75, 23);
            this.AddBtn.TabIndex = 2;
            this.AddBtn.Text = "Add";
            this.AddBtn.UseVisualStyleBackColor = true;

            this.Controls.Add(AddBtn);

        }

        // Adds products to the listview
        private void AddProducts()
        {
            IDictionary<string, string> products = GetProducts();
            foreach (var p in products)
            {
                ListViewItem lstItem = new ListViewItem(p.Key);
                lstItem.SubItems.Add(p.Value);
                listView1.Items.Add(lstItem);
            }
        }

        // Gets the products
        private IDictionary<string, string> GetProducts()
        {
            IDictionary<string, string> products = new Dictionary<string, string>();
            products.Add("product a", "a");
            products.Add("product b", "b");
            products.Add("product c", "c");
            products.Add("product d", "d");
            return products;
        }

'개발언어 > C#' 카테고리의 다른 글

[C#] ListView 실습  (0) 2021.08.10
[C#] listview에 button추가시 샘플3  (0) 2021.08.10
[C#] 버튼 button의 값넣기 Tag  (0) 2021.08.10
[C#] ListView 사용법  (0) 2021.08.10
[NAudio] 7. Visualization  (0) 2021.07.08