How to fill Data Grid View dynamically (run time) in C# Win-Forms
Solution 1
Here is the demo for you. I suppose your data is of type Info
as defined below, you can change the Properties
accordingly depending on your data structure (which is received from the hardware):
public partial class Form1 : Form {
public Form1(){
InitializeComponent();
dataGridView1.AllowUserToAddRows = false;//if you don't want this, just remove it.
dataGridView1.DataSource = data;
Timer t = new Timer(){Interval = 1000};
t.Tick += UpdateGrid;
t.Start();
}
private void UpdateGrid(object sender, EventArgs e){
char c1 = (char)rand.Next(65,97);
char c2 = (char)rand.Next(65,97);
data.Add(new Info() {Field1 = c1.ToString(), Field2 = c2.ToString()});
dataGridView1.FirstDisplayedScrollingRowIndex = data.Count - 1;//This will keep the last added row visible with vertical scrollbar being at bottom.
}
BindingList<Info> data = new BindingList<Info>();
Random rand = new Random();
//the structure of your data including only 2 fields to test
public class Info
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}
}
Solution 2
if you get the data some where in the object or variable, then this will work for you.
// suppose you get the data in the object test which has two fields field1 and field2, then you can add them in the grid using below code:
grdView.Rows.Add(test.field1, test.field2);
I hope it will help you.. :)
Anoop
Updated on June 04, 2022Comments
-
Anoop almost 2 years
I have one application which can communicate with a connected hardware. When I turn on the hardware, the hardware will continuously send some data to the application. I am able to read the data from hardware in my application.
Now I want to record this data to a Grid View continuously(whenever the application receive data, a new row needs to be added to the Grid View and fill the data in that row).
(Or please show me how to add new row in a grid view in each 1 second and add some data in to it at run time)
Please help. I am new to c#.
Thanks.