Search code examples
c#winformsdatagridviewdatagridviewcolumn

How to define columns in datagridview programmatically?


I`m making windows application

I added 1 button and 1 datagridview.

when click the button, data showed in datagridview from DB.

And this step, I have a question.

I want to define DataGridView Columns programmatically like this

  1. First column = check box column
  2. Second column = Process column(I want to bind data here)
  3. Third column = Progress bar column(I`ll make this column)

SQL query is below

SELECT COUNT(*) as Process from Sales.SalesOrderDetail
UNION
SELECT COUNT(*) as Process from Purchasing.ProductVendor
UNION
SELECT COUNT(*) as Process from Person.Address
UNION
SELECT COUNT(*) as Process from Production.WorkOrder

And button click event is like this

private void btnStart_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AdvConn"].ConnectionString);
    SqlCommand cmd = new SqlCommand("UP_SelectTableCount", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    try
    {
        conn.Open();

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
    }
    catch{}
    finally
    {
        conn.Close();
    }
    dt = ds.Tables[0];
    metroGrid2.DataSource = dt; }

How can I add or fix my code? please help me

Thanks.


Solution

  • After the data has been added to the datagridview you can write a simple function for adding a new column like this

    private void AddNewColumns()
    {
        metroGrid2.Columns.Add("newColumnName", "Column Name in Text");
        //To add values to the column you should run a foreach loop 
        foreach (DataGridViewRow row in metroGrid2.Rows) 
        {
            if (row.Cells[1].Value.ToString()=="1") //Some condition or value  
                row.Cells[2].Value = "50%"; 
        }
    }
    

    This is just an idea about adding a column but not about adding a progress bar. But I believe this might help you because your main concern is to add a new column to the DGV. Hope this helps

    For adding a progress bar column Populating a DataGridView with Text and ProgressBars might help you