T
T
Therapyx2015-08-02 02:13:24
SQL
Therapyx, 2015-08-02 02:13:24

Select request via c#, what's the problem?

string Query;
            try
            {              
                if (!string.IsNullOrEmpty(txtSelectByDate1.Text) && !string.IsNullOrEmpty(txtSelectByDate2.Text))                
                     Query = "Select * from Purchase where P_Date >= '"+Convert.ToDateTime(txtSelectByDate1.Text).ToString("yyyy-MM-dd") + 
                     "' and P_Date <= '" + Convert.ToDateTime(txtSelectByDate2.Text).ToString("yyyy-MM-dd") + "'";
                SqlCommand cmd = new SqlCommand(Query, cn);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                gvPurchase.DataSourceID = null;
                gvPurchase.DataSource = dt;
            }

In this line, Query gets an error with the description "Use of unassigned local variable 'Query'"
SqlCommand cmd = new SqlCommand(Query, cn);
If you remove this check, then everything works fine.
if (!string.IsNullOrEmpty(txtSelectByDate1.Text) && !string.IsNullOrEmpty(txtSelectByDate2.Text))

Why does it come out like this? Or what way of checking two text boxes for the presence of information would be suitable in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
ar4ebaldello, 2015-08-02
@Therapyx

So why are you running a query if you don't initialize query?

var dateFromString = txtSelectByDate1.Text;
var dateToString = txtSelectByDate2.Text;

if (!string.IsNullOrEmpty(dateFromString) && !string.IsNullOrEmpty(dateToString))                
{
    var dateFrom = Convert.ToDateTime(dateFromString).ToString("yyyy-MM-dd");
    var dateTo = Convert.ToDateTime(dateToString).ToString("yyyy-MM-dd");
    
    var query = string.Format("Select * from Purchase where P_Date >= '{0}' and P_Date <= '{1}'", dateFrom, dateTo);
    
    var command = new SqlCommand(query, cn);
    var adapter = new SqlDataAdapter(command);
    var table = new DataTable();
    adapter.Fill(table);
    
    gvPurchase.DataSourceID = null;
    gvPurchase.DataSource = table;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question