Click here to Skip to main content
15,917,731 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
using a datagridview to add data to a table. So i want to make everytime someone adds a new record in the datatable, a cell will receive a datetime value. So i did this:

DataGridView.CurrentRow.Cells[dataGridViewTextBoxColumn].Value = DateTime.Now;

the problem is that this gives an error and i don't know where to change. Can anyone give me a hint?

I test you code it execute without error.
Please attend to bellow point:
1)This code is OK.
dataGridView1.CurrentRow.Cells[YourColumnNumber].Value = DateTime.Now;

2)The first column number is zero, therefore if you want add date to third column you must use from 2 az YourColumnNumber

3)You can use from upper code in Button_Click

I hope it's helpful
Share this answer
The reason for the compiler error is you have used the dataGridViewColumn object to access the cell which accepts the Column index or name. Change your code like
DataGridView.CurrentRow.Cells[columnIndex].Value = DateTime.Now; or
DataGridView.CurrentRow.Cells[columnName].Value = DateTime.Now; 
where columnIndex/columnName is the number/Name that represents your column.
Share this answer
Just want to thank you Both. I was using the column name. But after reading your help, i realized it's simpler to use the index. But the error persisted. Left the code for a while, when came back i saw where i was wrong. It was wrong index. The datetime valu should go to [4] and i was giving to index [5] that is a string. The error message was pretty clear, but sometimes the brain sees everything but that. Thank you alot guys.
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