Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 12555
  • Last Modified:

How to refresh a DataGridView?

All,
i have a datagridview, the data source of it is a List. what i want to do are:
1. Add new data to the list
2. bind the list to dataGridView
3. refresh the dataGridView
example:
lstGrpMaster.Add(Master1);
dataGridViewMaster.DataSource = _lstGrpMaster;
dataGridViewMaster.Refresh();

the above code does not work. Do you have any idea?
thanks a lot
viola
0
viola123
Asked:
viola123
1 Solution
 
Wayne Taylor (webtubbs)Commented:
Hi viola,

Instead of dataGridViewMaster.Refresh(), use dataGridViewMaster.Databind().

Regards,

Wayne
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
the direct answer to that is to set the DataSource to null before setting it to the actual datasource.
This will force the datagrid to "refresh" itself.

BUT...
If the datagrid have the DataSource property set, changing the datasource will automatically show on the grid.

Try the example bellow:
Drag a DataGridView and a button into an empty form.
Paste the code bellow into the form.

Run the project and click the button, you'll see the rows appearing and I'm not running any refresh code.

            DataTable dt = new DataTable();
            private void Form1_Load(object sender, EventArgs e)
            {
                  
                  dt.Columns.Add("Column1", typeof(int));

                  DataRow nr = dt.NewRow();
                  nr["Column1"] = 1;
                  dt.Rows.Add(nr);

                  nr = dt.NewRow();
                  nr["Column1"] = 2;
                  dt.Rows.Add(nr);

                  this.dataGridView1.DataSource = dt;
            }

            private void button1_Click(object sender, EventArgs e)
            {
                  DataRow nr = dt.NewRow();
                  nr["Column1"] = 1;
                  dt.Rows.Add(nr);
            }
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
Forgot to ask, is this windows or web?

I assumed it's windows because windows grid is called dataGridView and the web GridView have no Refresh method.
0
 
viola123Author Commented:
All,
thanks. i figured it out, you have to set the datasource to Null first and then assign the datasource again.

AlexCode: it is windows application.

0
 
SamooramadCommented:
nevermind, stupid question. I had the dataset size set incorreclty. Thanks
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now