Sumitra Paul

Sumitra Paul

  • NA
  • 51
  • 33.7k

Adding editable rows dynamically to listview (c# windows for

Apr 28 2013 9:44 AM

Hi,

I am new to c# windows application.
I have added a listview programatically to c# win form. I want to add a listview row (editable row) dynamically on click
of Add button so that user can type new items and save it.

Please see the code which adds a listview and adds some item to the list view.

private ListView listView1;
        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;
        }


Is it posible to add a new editable row to the listview so that user can type a new product name and new search string
and save it using another save button.

Thanks for the help. Your help will be heighly appriciated.

Thanks.
Regards


Answers (1)