Reputation: 5136
I have this Code
foreach (DataGridViewRow dgr in DataGridView1.Rows)
{
if(dgr.Cells["TillDate"].Value != null )
dgr.Cells["dgColTillDateCalculate"].Value =
(DateTime)dgr.Cells["TillDate"].Value ;
}
EDITED
Where cell TillDate
is of DataGridViewDateTimeCell
I want to short this code of Condition within foreach Loop into one line is there any way to do this like
dgr.Cells["dgColTillDateCalculate"].Value =
(DateTime)dgr.Cells["TillDate"].Value == null
? doNothing
: dgr.Cells["TillDate"].Value;
What should i do at doNothing
please suggest more efficient way ..
Upvotes: 0
Views: 115
Reputation: 2550
You could move the if
into the foreach using linq which would simplify the line inside:
foreach (DataGridViewRow dgr in DataGridView1.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["TillDate"].Value != null))
{
dgr.Cells["dgColTillDateCalculate"].Value = (DateTime)dgr.Cells["TillDate"].Value;
}
Upvotes: 2
Reputation: 28403
Try This
foreach (DataGridViewRow dgr in DataGridView1.Rows)
{
dgr.Cells["dgColTillDateCalculate"].Value =
(DateTime)dgr.Cells["TillDate"].Value == null
? (DateTime?)null
: dgr.Cells["TillDate"].Value;
}
Upvotes: 2
Reputation: 3834
Here it is:
dgr.Cells["dgColTillDateCalculate"].Value =
dgr.Cells["TillDate"].Value == null
? (DateTime?)null
: dgr.Cells["TillDate"].Value;
But since you was assigning value to dgr.Cells["dgColTillDateCalculate"].Value
, check if null
value required for assigning or not.
Upvotes: 1
Reputation: 11903
I think that your original code is perfect, you shouldn't change it. Anyway, replace doNothing
with dgr.Cells["dgColTillDateCalculate"].Value
, so it will get back its original value.
Upvotes: 0