简体   繁体   中英

Add unbound column to datagridview after setting DataSource property of grid?

I'm wondering how can I create and fill unbound columns values after setting DataSource property of DataGridView. Suppose we have two simple table in our database: tblTest:

  1. ID (int)
  2. Fname (nvarchar(50)
  3. Population (int)

I have datagridview named grid in my form1:

DataTable tblTest = new DataTable();//Select * from tblTest
...
grid.DataSource = tblTest;
????

What will I replace with ??? to add unbound Percent column that show percentage of population over all data in tblTest rows. Our calculation must happen in code side not in DB side... thank you :)

Just add column to DataTable and use it in same way for adding to grid DataSource

DataTable tblTest = new DataTable(); //SELECT * FROM YourTable

//Calculate sum of population
Decimal overall = tblTest.AsEnumerable().Select(dr => dr.Field<Decimal>("Population")).DefaultIfEmpty().Sum();

tblTest.Columns.Add("Percentage", typeof(Decimal));
foreach(DataRow drow in tblTest.Rows)
{
    Decimal percentage = YourPercentageCalculationResult; //Add you calculation

    drow.SetField<Decimal>("Percentage", percentage);
}

//Create column "on runtime"
DataGridViewTextBoxColumn temp = New DataGridViewTextBoxColumn();
temp.DataPropertyName = "Percentage"
temp.ReadOnly = true;
grid.Columns.Add(temp);

grid.DataSource = tblTest;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM