Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add rows to datagridview winforms? [duplicate]

I want to add rows to a datagridview. I tried a lot of possibilities, but it doesn't appear anything on it. I think the best solution is to create a datatable, and then to use it as datasource for my gridview. I use winforms. Please, any other idea is welcomed . This is what I have tried so far:

public DataTable GetResultsTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Name".ToString());
        table.Columns.Add("Color".ToString());
        DataRow dr;
        dr = table.NewRow();
        dr["Name"] = "Mike";
        dr["Color "] = "blue";
        table.AcceptChanges();
        return table;
    }
public void gridview()
{
     datagridview1.DataSource=null;
     datagridview1.DataSource=table;
}
like image 487
Viva Avatar asked Apr 12 '13 06:04

Viva


4 Answers

i found two mistake in your code:

  1. dr["Color "] = "blue"; Column Color should without space dr["Color"] = "blue";
  2. You forgot to add row to the table

    table.Rows.Add(dr);

you can try this

public DataTable GetResultsTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Name".ToString());
    table.Columns.Add("Color".ToString());
    DataRow dr = table.NewRow();
    dr["Name"] = "Mike";
    dr["Color"] = "blue";
    table.Rows.Add(dr);
    return table;
}
public void gridview()
{          
    datagridview1.DataSource =  GetResultsTable();
}
like image 137
Arshad Avatar answered Nov 18 '22 02:11

Arshad


There are different ways , but in different conditions.

As my following code shows you gridview.add method in case of string array:

datagridview1.Rows.Add( { val, val, val });

It depends upon context and situation at which you want to apply it.

like image 32
Freelancer Avatar answered Nov 18 '22 01:11

Freelancer


Try This method:

dataGridView1.Columns.Add("Col1", "Name"); // "Col1" is the name of the column and  "Name" is the column header text"
dataGridView1.Columns.Add("Col2", "Age");
dataGridView1.Rows.Add("ABC", "25");

Hope this helps :)

like image 3
Praveen VR Avatar answered Nov 18 '22 00:11

Praveen VR


DataGridView dgv = new DataGridView();

DataTable table = new DataTable();

dgv.DataSource = table;

table.Columns.Add("Name");
table.Columns.Add("Color");
table.Rows.Add("Mike", "blue");
table.Rows.Add("Pat", "yellow");

this.Controls.Add(dgv);
like image 2
user2141886 Avatar answered Nov 18 '22 00:11

user2141886