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;
}
i found two mistake in your code:
dr["Color "] = "blue";
Column Color should without space dr["Color"] = "blue";
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();
}
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.
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 :)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With