0

I am working on a windows form application in C# , I have a data grid view which its DataSource is coming from a DataTable just like this

 DataTable table = projectsOperations.GetPaymentsByProjectId(this.ProjectID);

        dgvShowPaymentsOfProject.DataSource = table;

now i need to change the width of the column number 7 in the DataGridView i have tried this :

            dgvShowPaymentsOfProject.Columns[7].Width = 200;

but i gives me an exception "Object reference not set to an instance of an object" can you guys please help?

  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – John Sep 29 '22 at 04:36
  • Fun fact: column 7 would be `dgvShowPaymentsOfProject.Columns[6].Width = 200;` arrays and collections are zero based in c#. Chapter 1 level stuff – Ňɏssa Pøngjǣrdenlarp Sep 29 '22 at 04:55
  • thanks , but this does not answer my question , i am still getting the same exception – Ali Mustafa Sep 29 '22 at 05:01

1 Answers1

0

Try following code:

DataGridViewColumn column = dgvShowPaymentsOfProject.Columns[7];
column.Width = 200;

Or you can set auto size mode:

  dgvShowPaymentsOfProject.AutoSizeColumnsMode = 
        DataGridViewAutoSizeColumnsMode.AllCells;

Or

dgvShowPaymentsOfProject.Columns[7].FillWeight = 200;

In addition, the number of indexes in DataGridView and also in DataTable starts from zero. If you have 7 fields and the field you want is the last field, i.e. the seventh field, you should introduce field number 6. for example:

DataGridViewColumn column = dgvShowPaymentsOfProject.Columns[6];
column.Width = 200;

The above code is applied to the seventh field. And lastly, execute these codes after connecting the data source to the DataGridView. If you run before that, you will most likely get an error.

AliNajafZadeh
  • 1,216
  • 2
  • 13
  • 22