Click here to Skip to main content
15,847,903 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to set data source of one combo box to one column of table and this combo box is one of gridview column my code is :
C#
DataTable p = new System.Data.DataTable();
            p = selectcolor();
            (dataGridView1.Columns[4] as DataGridViewComboBoxColumn).DataSource = p;
 


private DataTable selectcolor()
       {

           DataTable k = new System.Data.DataTable();
           try
           {

               string str = "Data Source=C:\\Documents and Settings\\almas\\Desktop\\BazarKhodro\\khodro.sdf";
               Qconnection.ConnectionString = str;
               Qcommand.Connection = Qconnection;


               string commandText = "select color from foroosh";

               Qcommand.CommandText = commandText;
               Qcommand.CommandType = CommandType.Text;
               SqlCeDataAdapter a = new SqlCeDataAdapter();
               a.SelectCommand = Qcommand;
               a.Fill(k);
               Qconnection.Open();
               Qconnection.Close();
               return k;

           }
           catch (Exception ex)
           {

               throw new Exception(ex.Message);
               return k;
           }
       }


after runing i see the content of p but 0ccur this error

Object reference not set to an instance of an object.

pls help me
Posted
Updated 7-Nov-12 23:05pm
v2

1 solution

The error is because your cast isn't working:

C#
(dataGridView1.Columns[4] as DataGridViewComboBoxColumn).DataSource


http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx[^]

If this type of cast doesn't work, it simply returns null, so you're trying to set the .DataSource property on an object that is null.

I can't say why the cast isn't working but you need to check that dataGridView1.Columns[4] is not null and that dataGridView1.Columns[4] is of type DataGridViewComboBoxColumn before you cast.
 
Share this answer
 
Comments
f.sarikhani 8-Nov-12 4:45am    
with seting type of grideview1.column[4] to combo box my problem is solved but show System.Data.DataRowView in combo box
jim lahey 8-Nov-12 4:47am    
If this is a new issue, please post as a new question or it will get lost in all the comments.

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