Home » Windows OS

DataGridView. Set Column Type to notNull

Hi to Everyone,

Is it possible to set a datagridview column value behavior to not null?

When a returned from DataAdapter (after SQL statement) datatable assigned to datagridview datasource property, then datagridview changes its column values according to DB table description: If the column is not nullable - datagridview controls the value itself.

Is it possible to do the same by setting a property of the datagridview object, without using EndEdit and such?




4 Answers Found


Answer 1

Try this DataGridView1.Columns("ColumnName").DefaultCellStyle.NullValue = "Default Value"

Answer 2

Well, it's ok. thanks. but what I'd like to get is a warning from datagridview  with info just like "the value can't be set  to null".

Answer 3

You are getting error message because of schema design in data source  ( your database table). Above settings will just display a value to the cell, it won't make any changes to 'Row State'.

Other option is 'Table Mapping ' DataTable as per requirement and assign to datagridview's data source.

Use this link for details http://msdn.microsoft.com/en-us/library/ms810286.aspx


Answer 4

Hi Robbirk,

   Welcome to MSDN forums! I'm glad to see your active participation and discussion in MSDN forums. Based on your issue 

  set  a datagridview  column value behavior  to not null?

    dataGridView1.Columns["coulmnName"].DefaultCellStyle.NullValue = "null";

 but what I'd like to get is a warning from datagridview with info just like "the value can't be set to null".   

        public Form2(){


            dataGridView1.CellValidating +=new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);


        protectedvoid dataGridView1_CellValidating(object source, DataGridViewCellValidatingEventArgs e)


            if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null |

                  dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == string.Empty)

                MessageBox.Show("the value can't be set to null");

                e.Cancel = true ;



 Hope this will help you!  

   If you still have any doubt and concern about this issue, please let me know. If I misunderstood you, please kindly elaborate your question.



I have a column called regdate datetime default getdate() , the column is notnull.
I am using linq to sql.
I have created instance of that table and when i try to insert record into the table, I am getting daterange exception.
(range should be 1/1/1753 to 31/12/9999).
In that object I am not setting any value to regdate property as that would be taken care by sql server.

If i set regdate = datetime.now.date then record is inserted successfully.

I dont want to set any value from front-ent.
I want sql server to do that for me like we do it using stored procedure.

Please guide me who to do this?




There is a new setting for lists in 2010 called "Column default value settings". What lists does this setting apply to (I think just lists with a base template of Document Library)? And for what column types is it available? It was available on a "Single line of text" column but not a lookup column.

Thanks in advance!


In my application I read data (using data binding) from an Excel spreadsheet into a DataGridView. This works, but the data columns contain text fields (strings). I would like to set the data type for some columns to "Date" and Decimal. I cant do this on the DataGridView (error: cant change properties for data-bound stuff) and I cant figure out how to do it on the dataset or data-table that I bind to the DataGridView.

The following is the code I use to read and bind the data: 

 Using con As OleDbConnection = New OleDbConnection(cs)


    'open the OleDbConnection



    Using da As OleDbDataAdapter = New OleDbDataAdapter(sqlCmd, con)

     da.TableMappings.Add("Table", "Details")


     'use table adapter to fill a DataSet

     Using ds As New DataSet()


      'Todo: Set the column data types


      'ds.Tables(0).Columns.Add("Date", GetType(Date))

      'ds.Tables(0).Columns.Add("Closing", GetType(Decimal))



      grid.DataSource = ds.Tables(0).DefaultView

     End Using

    End Using


   End Using

The commented out code (below the 'Todo: comment) causes a additional table, but I want to change the table with the data. Any help will be appreciated.




How do I assign a 'data type' to an 'unbounded' datagridview object
I am trying to change datagridview column type from DataGridViewTextBoxCellto DataGridViewComboBoxCell at run time for just one row. I can get the combo box to show up on the particular row, but 
it only fills with the first item. What have I missed?
int RW_DESC = 2;
nRowNum = 25;
DataGridViewComboBoxCell cb = new DataGridViewComboBoxCell();
this.tbl_ssi_EstOfCostDataGridView[RW_DESC, nRowNum] = cb;


Hi all,


Is there any way  to have a datagridview column type of datetimepicker format or something like that? If yes, how?







I am getting an argument out of rance exception error when trying to set the DGV column names.  I set the Datasource of the DGV in another function then  immediately call this code to set up column name information for the DGV



void SetUpGrid()



//dgvJobData.AutoGenerateColumns = false;

dgvJobData.AllowUserToAddRows =


dgvJobData.AllowUserToDeleteRows =


dgvJobData.AllowUserToResizeColumns =


dgvJobData.AllowUserToOrderColumns =


dgvJobData.Columns[0].AutoSizeMode =


dgvJobData.Columns[0].HeaderText =

"Job ID";


dgvJobData.Columns[1].AutoSizeMode =


dgvJobData.Columns[1].HeaderText =


dgvJobData.Columns[2].AutoSizeMode =


dgvJobData.Columns[2].HeaderText =


dgvJobData.Columns[3].AutoSizeMode =


dgvJobData.Columns[3].HeaderText =

"Job Fixed";

dgvJobData.Columns[4].AutoSizeMode =


dgvJobData.Columns[4].HeaderText =

"Job Start";

dgvJobData.Columns[5].AutoSizeMode =


dgvJobData.Columns[5].HeaderText =

"Job Close";

dgvJobData.Columns[6].AutoSizeMode =


dgvJobData.Columns[6].HeaderText =

"Latest End Time";

dgvJobData.Columns[7].Visible =

false; // Hide the status column

dgvJobData.Columns[8].Visible =

false; // Hide the alert status column


When the code hits the first Column[0] line it throws the exception with the following message:-

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Any help would greatly be appreciated






I have put a DataGridView in my program such that this DataGridView is corresponding to a dataset of one table and this table has a auto-incremented identity column(also,this column is set to be primary key).

This identity column is not visible in DataGridView and when a user fills other cells and clicks "save",NoNullAllowedException occurs.

Why?I want to allow user to just insert data(not another modification)

How can I do?I use C# and SQL server 2008



I have a datatable that adds three columns automatically to a datagridview. Then I want to add a button column that is not from a datasource. The button column has an index of 3 which my program relies on. After a few refreshes of the grid the button column ends up being in the front at index 0. What is the standard operating procedure for adding columns after setting the datasource so the columns maintain the right order? I don't want to have to loop over every column every time I want to get a cell. Here is the code to set the datasource and then add a column.

m_VariableDataGrid->DataSource = nullptr;
m_VariableDataGrid->DataSource = m_VarTable->DefaultView;

How can I make sure m_pInfoColumn stays at index 3 assuming the datatable has three columns?


this is my code

frmmain  is my main form.and  frmpayable is frmmain's child from.in the frmpayable my code is

 Dim frmreleasing As frmPostap
 frmreleasing = New frmPostap(Me, release_record)
 frmreleasing.MdiParent = Me.MdiParent

so in the frmreleasing the checkbox in the datagridview can not selected when load.


I have a DataGridView and im trying to set one column's font style to Bold. So in design view i goto Columns collection select the column i want and then set the Column's Default Cell Style. But it doest get set. At run time i still see the column's text is regular size instead of bold.



I have 2 datagridviews on different tabs of a tabcontrol.

The user can input names into datagridview1 column1. I want these names to automatically appear in datagridview2 column1, in such a way that when rows in datagridview1 are added and removed the same rows are added and removed in datagridview2. I also want the column sort function to effect datagridview2.





I'm building a custom list with several columns, including a Calculated column.
This calculated column simply takes the value of a choice column in the same list to convert this value to a single line of text value.
I do this because when adding a lookup column to this list, I cannot select Choice columns as additional columns, but I can add the calculated column.

Speaks for itself that this calculated column only needs to exist in the background, and end users should not see this column in the Add/Edit/Display forms.
In add/edit forms the column is not displayed, but in the display form it gets displayed.

Piece of cake I thought, I'll just set it as hidden in the content type used for the list.
When I open the column the column settings (required/optional/hidden) is grayed out, so I cannot set it to hidden.

In SP2007 this was possible, why can't I do this anymore in SP2010?
Do I miss some feature in order to do this, or is there a good reason why this seems to have changed in SP2010?


hello,every body!my question as follows

first,i have set the datagridview's DefaultCellStyle.ForeColor = SystemColors.InactiveBorder

but,as i see in my program interface,The forecolor of datagridview's first row is black.

With grdCustomerInformation
 .DefaultCellStyle.ForeColor = SystemColors.InactiveBorder
End With

Dim row_1 As String() = New String() {"Name"}

Dim row_2 As String() = New String() {"Address Line 1"}

Dim row_3 As String() = New String() {"Address Line 2"}

Dim row_4 As String() = New String() {"City", "St", "Zip"}

Dim row_5 As String() = New String() {"Country"}


Hai friends,

I've a datagridview using C# .net which has been get data fields from MySql and displays like


FirstName    |    LastName   |    ID   


Kelvin          |    David         |   001

Maria           |    John           |   002

Joe              |    Martin         |   003


This above example shows the datas with 3 fields which is in MySql dataBase Table name "Details"

I want to display it in my datagridview as like give below




Kelvin  David  001

Maria  John    002

Joe  Martin 003


This is showing in a single field. And it should be with the same table "Details"

Waiting for Answer...

Thank you....


I am new to using VB Express (2008 and 2010). I have an .mdb database with 4 tables. I am able to show a detail form with a couple of comboboxes linked to their related tables so as to show Name rather than the numeric foreign key.

Now I am trying to link the same foreign-key columns in a DGV to show Name and not the key, but can't figure out how to achieve that?

The answer may already be in this forum, but I can't find it!!

Can somebody help me, please?

Cheers, Bill



I have the following code to add a new column into the datagridview but how to default value to this column?

I do not want to use for loop to loop through each row and get the column updated, is there any other way?

I want to default them to 'N' and i will have the code to change it to 'Y' subsequently based on conditions.


        dgDataConfiguration.Columns.Add("Update", "Update")


Many thanks.


Does anyone know if it's possible to prevent users from changing the Content Type property of a document once that document has been added to a library.

We have several libraries that support multiple Content Types.  When users upload a new document, they can select the Content Type from the picklist on the checkin/properties screen.  That is as desired.  However, should a user edit the properties of an existing document, we would like to prevent them from changing the Content Type at that point. 

The reason is that when the document is initially created and saved, we set some column values specific to that Content Type using an EventReceiver.  if the user later comes back and changes the Content Type, new type-specific columns are set, but the old columns still exist in the library and maintain the original value (which no longer apply to the document, however).

The easiest way to deal with this would be to prevent users from changing the Content Type once a document has been created...if that's possible.  An alternative would be to blank out the old column values in the EventReceiver, but I can't seem to access those columns anymore once the user has changed the Content Type -- they end up being non-instantiated objects when I try to access them.

Does that make sense? Anyone run across a similar situation? Thoughts? Kind of new at the whole SP Programming piece so looking for any ideas....





i created a csv file with infomation of appointment,all the columns are OK execpt the "organzier"(partytylist) and "status" (status). i dont acheive it because this 2 colume, is it possible to import these using import wizard?

and i found there can only be one user in the field of organzier, but why it is not lookup type...



I have an odd issue that I cannot figure out for the life of me.  I have two computers (Desktop and Laptop) both running the same version of SSMS (R2 10.50.1600.1).  When I am in the table design view on my desktop I cannot just type the data type into the Data Type column.  I have to select it from the drop down, then edit the length if I need to.  However on my laptop I can just type the data type into the column with no issue.  

I know this seems like a minor issue, however it is very frustrating.  I have compared the settings on both machines and I cannot find a difference.  Does anyone have any idea why I can't just type the data type into the SSMS table designer on my desktop?




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure