Reputation: 329
I create a function. Where date can be selected by the user . And when the user not select the date i want to pass null .
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And this is the code part where i am calling the function
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize, clientid, Convert.ToDateTime(txtFirstDate.Text.Trim()), Convert.ToDateTime(txtLastDate.Text.Trim()), txtInvoiceNumber.Text.Trim(), ref invoicecount);
Sometime the user cant fill the txtFirstDate.Text
but i am converting Convert.TodateTime() so how can i fix this because when user not fill the datetime it give me exception. So how can i handle this .
Upvotes: 0
Views: 613
Reputation: 1620
For any dates you want to be able to accept as null, like DateTime startDate
you need to make them nullable like DateTime? startDate
And then before you call GetInvoicebyPaging
try and sort out the datetimes.
DateTime startDate;
var correctStart = DateTime.TryParse(txtFirstDate.Text.Trim(), out startDate);
And then pass the parameter like
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize,
clientid, (correctStart ? startDate : null), etc
And you may have to check if txtFirstDate.Text
is null as well.
After declaring startDate
above you can do:
var dateString = txtFirstDate.Text ?? "";
And pass dateString.Trim()
into the DateTime.TryParse
Upvotes: 0
Reputation: 19712
You need to change your method to:
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime? startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And when you parse the user data you can do:
DateTime? start = null;
DateTime possibleStartValue;
if(!string.IsNullOrEmpty(txtTextBox.Text) && DateTime.TryParse(txtTextBox.Text, out possibleStartValue))
{
start = possibleStartValue;
}
Upvotes: 1
Reputation: 17614
You can create a nullable date time variable as follows
DateTime? value = null;
and pass as a parameter
In your function you can use like DateTime? value
as parameter
So you will have to do the following step
DateTime? startDate=txtFirstDate.Text.Trim()==""?null:Convert.ToDateTime(txtFirstDate.Text.Trim());
change your function argument so that it can take null value as above.
Upvotes: 0