Click here to Skip to main content
15,911,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I tried to insert data into datagrid view. But the think is when i tried to insert second row, it replace the existing row in datagrid cell. Can anyone help me to display multiple rows in datagrid view cell without database connection?

What I have tried:

C#
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;
using System.Web;

namespace task2
{
    public partial class Form1 : Form
    {
        private DataTable myTable = new DataTable();

        public Form1()
        {
            InitializeComponent();
            this.initialiseTable(this.myTable);
            this.dataGridView1.DataSource = this.myTable;
        }
        private void CLEAR_Click(object sender, EventArgs e)
        {
            Name.Text = "";
            LastName.Text = "";
            lsGender.Text = "";
            phone.Text = "";
            mail.Text = "";
        }
        private void CLOSE_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void initialiseTable(DataTable table)
        {
            table.Columns.Add(new DataColumn("Column1"));
            table.Columns.Add(new DataColumn("Column2"));
            table.Columns.Add(new DataColumn("Column3"));
        }


        private void ADD_Click(object sender, EventArgs e)
        {
            
           
            DataRow rd = this.myTable.NewRow();
            rd[0] = Name.Text;
            rd[1] = LastName.Text;
            rd[2] = lsGender.SelectedItem;
            this.myTable.Rows.Add(rd);
        }          
    }
}
Posted
Updated 5-May-16 20:58pm
v3

Strange: I copied your code into an app, added a DGV and a button, and it worked fine.
I'd suspect that you are closing the app and re-opening it, or using some code you don't show there.
Certainly, the code you show works fine here.
 
Share this answer
 
try this

C#
private void ADD_Click(object sender, EventArgs e)
       {

           DataRow rd = this.myTable.NewRow();
           rd[0] = Name.Text;
           rd[1] = LastName.Text;
           rd[2] = lsGender.SelectedItem;
           this.myTable.Rows.Add(rd);
           dataGridView1.DataSource = this.myTable; // add this line to bind the updated datatable to griview soruce

       }


The data will be present only till the life time of the application ( app opened and running ).. when it is closed the datatable will reset.
If you dont want to use DB and also to maintain the values, you shall use XML
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900