?
Solved

Better way to add rows to DataGridView?

Posted on 2011-04-27
3
Medium Priority
?
489 Views
Last Modified: 2013-12-16
I'm new to C#. What would be a better way to add a new row to the end of my DataGridView in method dgvaddrow below?
using System;
using System.Windows.Forms;
using System.Threading;

namespace dgvtest1
{
  public partial class Form1 : Form
  {
     delegate void AddRow(Cdata d);
     AddRow dmeth = null;

     public Form1()
     {
        InitializeComponent();
     }

     protected override void OnShown(EventArgs e)
     {
        ThreadStart Y = new ThreadStart(DoStuff);
        Thread tid1 = new Thread(Y);
        tid1.Start();
     }

     void DoStuff()
     {
        dmeth = new AddRow(dgvaddrow);
        Cdata d = new Cdata();
        d.C1 = "Hello";
        d.C2 = "Goodbye";
        d.C3 = "Three";
        this.Invoke(dmeth,d);
     }

     public void dgvaddrow(Cdata d)
     {
        int index = dataGridView1.Rows.Add();
        dataGridView1["Column1", index].Value = d.C1;
        dataGridView1["Column2", index].Value = d.C2;
     }

     public class Cdata
     {
        private string c1;
        private string c2;
        private string c3;

        public string C1
        {
          get { return c1; }
          set { c1 = value; }
        }
        public string C2
        {
          get { return c2; }
          set { c2 = value; }
        }
        public string C3
        {
          get { return c3; }
          set { c3 = value; }
        }
     }
  }
}

Open in new window

0
Comment
Question by:deleyd
3 Comments
 
LVL 11

Expert Comment

by:brutaldev
ID: 35478212
I don't know why you are doing this in a separate thread? You could change your code to this:
 
using System;
using System.Windows.Forms;
using System.Threading;

namespace dgvtest1
{
  public partial class Form1 : Form
  {
     public Form1()
     {
        InitializeComponent();
     }

     protected override void OnShown(EventArgs e)
     {
        Cdata d = new Cdata();
        d.C1 = "Hello";
        d.C2 = "Goodbye";
        d.C3 = "Three";

        dgvaddrow(d);
     }

     public void dgvaddrow(Cdata d)
     {
        int index = dataGridView1.Rows.Add();
        dataGridView1["Column1", index].Value = d.C1;
        dataGridView1["Column2", index].Value = d.C2;
     }

     public class Cdata
     {
        private string c1;
        private string c2;
        private string c3;

        public string C1
        {
          get { return c1; }
          set { c1 = value; }
        }
        public string C2
        {
          get { return c2; }
          set { c2 = value; }
        }
        public string C3
        {
          get { return c3; }
          set { c3 = value; }
        }
     }
  }
}

Open in new window

You may also want to lost the event handler and just put it straight in the constructor (after InitializeComponent). There are various other ways to attach your object to the grid (like data binding) but your code should work well for simply adding another row. The help on this shows a couple of other ways but I think you're on the right track.
0
 

Author Comment

by:deleyd
ID: 35479702
It ended up being in a separate thread so I could add a whole bunch of rows that would take awhile to do without hanging the rest of the program interface.

So I guess dataGridView1.Rows.Add is necessary to add a row, though I seem to end up with two rows when I run this demo—the row I added plus a blank row at the bottom.

So
1. Add blank row
2. Fill in columns of new row

Is there a way I could do it the other way, something like
DataGridViewRow ds = new DataGridViewRow();

Open in new window

followed by somehow filling in the columns of ds, then adding ds to the dataGridView?
0
 
LVL 10

Accepted Solution

by:
Nash2334 earned 2000 total points
ID: 35482944
You don't have to add a new row and populate values manually and you certainly don't need to do so in a separate thread if the DataGridView is bound to an underlying DataSource, such as a DataTable or BindingSource bound to a DataSet.  DataBinding takes care of all that for you.

Also, you see the additional row at the bottom because the DataGridView has a property called "AllowUserToAddRows".  Set this to false in the Designer or in code and you won't see it.

To see what I mean, create a new form, add a DataGridView and a Button.  Use the following sample code.

    public partial class Form1 : Form
    {
        private DataTable dt = new DataTable();

        public Form1()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.AllowUserToAddRows = false;

            // Create datatable
            dt.Columns.Add(new DataColumn("Int1", typeof(System.Int32)));
            dt.Columns.Add(new DataColumn("Int2", typeof(System.Int32)));
            dt.Columns.Add(new DataColumn("String1", typeof(System.String)));
            dt.Columns.Add(new DataColumn("Int3", typeof(System.Int32)));

            dt.BeginLoadData();
            DataRow dr = dt.NewRow();
            dr[0] = 1;
            dr[1] = 0;
            dr[2] = "Hello world.";
            dr[3] = 1;

            dt.Rows.Add(dr);
            dt.EndLoadData();

            // Bind it
            dataGridView1.DataSource = dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dt.BeginLoadData();
            DataRow dr = dt.NewRow();
            dr[0] = 1;
            dr[1] = 0;
            dr[2] = "Hello again world.";
            dr[3] = 1;

            dt.Rows.Add(dr);
            dt.EndLoadData();
        }
    }
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Loops Section Overview
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question