Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I'm trying to create the gridview columns and cell alignment at runtime but its throwing an error as "object referece not set to an instance of an object. What I did is:

C#
this.dataGridView2.Columns["ProductsSKUName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
this.dataGridView2.Columns["ProductsSKUName"].Name = DataGridViewContentAlignment.MiddleLeft.ToString();
Posted
Updated 20-Dec-10 18:39pm
v3

Maybe it throws an error because of misspelling "ProductsSKUNam" instead of "ProductsSKUName".

Edited:
You could set a breakpoint at the first line and check out the content of the this.dataGridView2.Columns collection. I think that it may be a problem of upper and lower case.
 
Share this answer
 
v2
Comments
krishna kishore58 21-Dec-10 0:39am    
No its actually ProductsSKUName.. I wrong pasted the code...
Vigneshb6 21-Dec-10 0:39am    
Nice Observation
Hi ,


The column name ["ProductsSKUNam"] is wrong, not defined in datagridview. Please check it.
 
Share this answer
 
Comments
krishna kishore58 21-Dec-10 0:43am    
Even when i change it to "Product" its throwing error...donno y...
vivekse 21-Dec-10 0:47am    
@krishan, if you created columns in design mode then check the column name.
if you binding a data source with list of class object then check the property of that class.
if you are binding with dataset or table then check the select statement column of your query.
krishna kishore58 21-Dec-10 1:08am    
if i create the columns at design mode its working fine but not at runtime...
vivekse 21-Dec-10 1:12am    
This working for me .
DataTable _dt = new DataTable();
DataColumn _dc = new DataColumn("Roll");
_dt.Columns.Add(_dc);
_dt.Rows.Add();
_dt.Rows[0][0] = "1";
_dt.Rows.Add();
_dt.Rows[1][0] = "2";
dataGridView1.DataSource = _dt;
this.dataGridView1.Columns["Roll"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight ;
krishna kishore58 21-Dec-10 1:39am    
k cool, for creting one column its okay..so if i wanna create more than one then do i need to repeat this steps with with different object names.
DataTable _dt = new DataTable();
DataColumn _dc = new DataColumn("Roll");
_dt.Columns.Add(_dc);
dataGridView1.DataSource = _dt;
this.dataGridView1.Columns["Roll"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
Hi ,

You have to read the Column with related Index.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900