Programmatically Add New Column to Datagridview

Programmatically add new column to DataGridView

Add new column to DataTable and use column Expression property to set your Status expression.

Here you can find good example: DataColumn.Expression Property

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

UPDATE

Code sample:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));

dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));

demoGridView.DataSource = dt;

UPDATE #2

dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

Adding new column to datagridview

It is so easy..

 dataGridView1.Columns.Add("Column","Test");

Add new column programmatically to DataGridView (DataGridview Filled with DataTable)

I am still unclear what you want. I will assume from the picture that you want the column “SrNo” to have the numbers 1, 2, 3… etc.… instead of the “pre-sorted” index order. This is doable; however, it appears there may be some confusion as to setting a cell value in the “grid” as opposed to setting a cell value in the data source.

Example, looking at the first code snippet the code gets a DataTable dTable from a data base. Then the code adds a column to the GRID. Then the data source is set to the grid. Then the GRID is sorted. Finally, a loop through all the rows in the GRID to set the SrNo values. This is straight forward and from my tests… this SHOULD WORK. You state that the column is empty however in my tests this code worked as expected with 1, 2, 3 … in the “SrNo" column. It is unclear where this code is called so I would conclude something else is going on after this code is called.

As other have commented, it may be better to put the column into the DataSource DataTable itself. This is doable, however, there is one problem from the approach you are using… you need to SORT the data table FIRST before you add the “SrNo” Numbers AND the table that we add the ”SrNo” column to CAN NOT be sorted. Therefore, you need to get a “new” table from the “sorted” table.

It is unclear why you do not do all this when you initially query the data base, however, below is an example of what I described above.

To start let us see “why” we can NOT use a “pre” sorted DataTable to add the numbers to. First, we get a data table. Then sort the data table, then use it as a data source to the grid. If we add the new column to the GRID, then… this works just fine. However, if we add the column to the DataTable and loop through all the rows in the data table like…

foreach (DataRow row in dTable.Rows) {
row["SrNo"] = srNo;
srNo++;
}

This is NOT going to work because the loop is NOT going to loop through the “sorted” order. This is what I meant earlier when I said. “it cannot be a sorted table.” With that said, it would appear that a simple solution would be to get a NEW table that is already sorted. THEN add the “SrNo” numbers to that table.

In the Example below, if you comment out the line…

dTable = dTable.DefaultView.ToTable();

you will see the items are not added in the proper order.

A global DataTable is used, however this is unnecessary.

DataTable dTable;

public Form1() {
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
//LoadDGV();
LoadDGV2();
}

LoadDGV() is the first snippet of code adding the column to the GRID and it works as expected.

private void LoadDGV() {
dTable = GetTable();
dgvDisplay.Columns.Add("SrNo", "Sr No"); // Adding "Serial No" Column to DataGridView
dgvDisplay.DataSource = dTable;
dgvDisplay.Sort(dgvDisplay.Columns["ID"], ListSortDirection.Ascending);
int srNo = 1;
foreach (DataGridViewRow row in dgvDisplay.Rows) {
row.Cells["SrNo"].Value = srNo++;
}
}

LoadDGV2() adds the column to the data table. The key line of code to make it work is… dTable = dTable.DefaultView.ToTable();

private void LoadDGV2() {
dTable = GetTable();
dTable.DefaultView.Sort = "ID";
dTable = dTable.DefaultView.ToTable();
dTable.Columns.Add(new DataColumn("SrNo", typeof(Int32))); // Adding "Serial No" Column to DataTable
int srNo = 1;
foreach (DataRow row in dTable.Rows) {
row["SrNo"] = srNo++;
}
dgvDisplay.DataSource = dTable;
}

A method to get some test data to complete the example.

private DataTable GetTable() {
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
Random rand = new Random();
for (int i = 0; i < 20; i++) {
dt.Rows.Add(rand.Next(1, 200), "Name_" + i);
}
return dt;
}

Hope that makes sense.

Add new column at specified position programmatically in C# Datagridview

Try dataGridView1.Columns.Insert(5, columnSave); instead.

MSDN reference: DataGridViewColumnCollection.Insert Method

Add Column and Rows in DataGridView c#

If you want to add rows from code try using DataTable and DataGridViewDataSource

string constring = @"Data Source=.\SQL2005;Initial Catalog=Northwind;User id = sa;password=pass@123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}

and other best way is to use Grapically
Sample Image

Comming to your problem

Seals_DataGridView.Columns.Add("column_Type", "Title Column");
Seals_DataGridView.Rows.Add("GOGO");

Code you given worked perfectly for me i don't know what the issue with your code you have to elaborate
Sample Image

Adding columns programmatically to DataGridView takes too long

Add the extra columns to the DataTable ahead of time. Fill them in when you have the data.

But then bind the DataTable to the DataGridView.

Dynamically/programmatically adding values to DataGridView

Here is a simple example on how to do it.

Here is the class of objects you want to display in the DataGridView. The things you want to display needs to be properties:

public class Fruit
{
public string Name { get; set; }
public Color Color { get; set; }

public Fruit(string name, Color color)
{
Name = name;
Color = color;
}
}

And here is the code for binding this data to the DataGridView. You need to link the name of the property to the dataGridViewColumn.DataPropertyName property.

// The list of objects
List<Fruit> fruit = new List<Fruit>( )
{new Fruit("Apple",Color.Red),
new Fruit("Orange",Color.Orange),
new Fruit("Pear",Color.Green)};

BindingSource source = new BindingSource(fruit, null);

dataGridView1.AutoGenerateColumns = false;

DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.HeaderText = "Name Of Fruit";
column.DataPropertyName = "Name"; // Name of the property in Fruit
dataGridView1.Columns.Add(column);

DataGridViewTextBoxColumn colorColumn = new DataGridViewTextBoxColumn();
colorColumn.HeaderText = "Color";
colorColumn.DataPropertyName = "Color"; // Name of the property in Fruit
dataGridView1.Columns.Add(colorColumn);

dataGridView1.DataSource = source;


Related Topics



Leave a reply



Submit