9

I use the following code to change the Column Name but unfortunately it won't let me do that. Please help me to solve this problem:

DateTime dt = DateTime.Now;
string s = dt.DayOfWeek.ToString();
for (int i = 0; i < 10; i++)
{
    dataGridView1.Columns.Add(string.Format("col{0}", i), s);
}
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    int c = dataGridView1.CurrentCell.ColumnIndex;
    string str = dataGridView1.Columns[c].HeaderText;
    if (str == "Wednesday")
    {
        str = "fifth day of week";
    }
}

Also is there any way so that I can get all day of week after each other between specific datetimes.

Any help will be appreciated

J. Murray
  • 1,460
  • 11
  • 19
  • Is there any type of error you are facing?? In your code you are not changing the column name anywhere instead you are assigning the column name to string variable `str` ? – Mr_Green Nov 15 '12 at 10:20
  • Possible duplicate of [Changing the column name in GridView using HTML or C#](https://stackoverflow.com/questions/7703548/changing-the-column-name-in-gridview-using-html-or-c-sharp) – mherzl Aug 06 '19 at 15:23

3 Answers3

16

You need to set DataGridView.Column[index].HeaderText:

DateTime dt = DateTime.Now;

string s = dt.DayOfWeek.ToString();
for (int i = 0; i < 10; i++)
{
    dataGridView1.Columns.Add(string.Format("col{0}", i), s);
}

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{

   string str = dataGridView1.Columns[i].HeaderText;
   if (str == "Wednesday")
   {
       dataGridView1.Columns[i].HeaderText = "fifth day of week";
   }
}
Danilo Vulović
  • 2,983
  • 20
  • 31
7

Add this line to Datagridview DataBindingComplete event handler

 this.dataGridView1.Columns["your database column name"].HeaderText = " preferred name";
rafalefighter
  • 714
  • 2
  • 11
  • 39
2

The below code will get all days of week after each other between specific datetimes and print the names of the days as column headers:

        DateTime dtStart = new DateTime(2012, 11, 1);
        DateTime dtEnd = new DateTime(2012, 11, 7);

        for (int i = 0; i < dtEnd.Subtract(dtStart).Days; i++)
        {
            TimeSpan counter = new TimeSpan(i, 0, 0, 0);

            dataGridView1.Columns.Add(string.Format("col{0}", i), (dtStart + counter).DayOfWeek.ToString());
        }  
03Usr
  • 3,335
  • 6
  • 37
  • 63
  • Thank you so much. i can't vote it up. because i have under 15 reputation. thankssss –  Nov 15 '12 at 11:04