0

How do I query multiple conditions, and when one of the conditions is empty is ignored, and the other conditions apply ?

this Is My Code

            var SalesAsInt = Convert.ToInt32(txtSalesNo.Text);
            var YearAsInt = Convert.ToInt32(cbxYear.Text);
            var MonthAsInt = Convert.ToInt32(cbxMonth.Text);
            var DayaAsInt = Convert.ToInt32(cbxDay.Text);
            using (var dbcontext = new Database.SalesEntities())
            {
                BindingSource VSalesIncome = new BindingSource();
                VSalesIncome.DataSource = dbcontext
                                 .VSalesIncomes
                                 .Where(u => u.SalesCode  == SalesAsInt )
                                 .Where(u => u.YearIncome == YearAsInt)
                                 .Where(u => u.MonthIncome == MonthAsInt)
                                 .Where(u => u.DayIncome == DayaAsInt)
                                 .ToList();

                dgvadministration.DataSource = VSalesIncome;
            }

Error When any text box is Empty

System.FormatException: 'Input string was not in a correct format.'

2 Answers 2

2

Try following two changes :

int? SalesAsInt = (txtSalesNo.Text == string.Empty) ? null : (int?)Convert.ToInt32(txtSalesNo.Text);

.Where(u => (SalesAsInt == null) ? true : u.SalesCode  == SalesAsInt )
Sign up to request clarification or add additional context in comments.

3 Comments

To expand on this answer. The first change covers the case of the Exception when you cannot convert from a value that is invalid. Second change is a simple boolean logic - each "Where" condition is checked against an item in your database and the item is returned if the Where returns true, so you want this to happen if the given filter matches or if the filter is empty.
this line int? SalesAsInt = (txtSalesNo.Text == string.Empty) ? null :Convert.ToInt32(txtSalesNo.Text); Error Severity Code Description Project File Line Suppression State Error CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int' Sales Saya World C:\Users\20101\Desktop\Sales Saya World\Sales Saya World\Report\frmSalesIncome.cs 39 Active
Convert.Toint32 returns a int so you need a cast : (int?)Convert.ToInt32(txtSalesNo.Text)
0

You can wrap your Where methods in if statements

var query = VSalesIncome.DataSource = dbcontext.VSalesIncomes
if (SalesAsInt > 0)
    query = query.Where(u => u.SalesCode  == SalesAsInt)
// repeat as needed
VSalesIncome.DataSource = query.ToList()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.