简体   繁体   中英

How to add columns dynamically to data grid view

I have two datetime variables Start Date and End Date.Suppose Start Date is 01-Jan-2013 and End date is 01-Mar-2013.Then I have to add datagridview columns as Jan,Feb,Mar. Please help me in achieving this.

Try this

string[] months = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

DateTime startDate = new DateTime(2013, 1, 1);
DateTime endDate = new DateTime(2013, 3, 1);

while (true)
{
   dataGridView1.Columns.Add(months[startDate.Month - 1], months[startDate.Month - 1]);
   startDate = startDate.AddMonths(1);
   if (startDate > endDate)
       break;
}

Of course you should make proper validation checks in this code too.

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