5

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;
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Viva
  • 1,983
  • 5
  • 26
  • 38

4 Answers4

11

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();
}
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
3

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.

Freelancer
  • 9,008
  • 7
  • 42
  • 81
3

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 :)

Denis Wasilew
  • 503
  • 3
  • 9
  • 29
Praveen VR
  • 1,554
  • 2
  • 16
  • 34
2
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);
  • Thank you very much! But also,it doesn't appear anything on my gridview. I can't explain why... – Viva Apr 12 '13 at 07:31