I have these three columns in UI. In dropdown I have a AllRecords
and some other field. I select that AllRecords
field and I enter start and end date details.
Now I write a query for that for retrieving the values.
When he select AllRecords
, depending upon start and end dates, it have to display OR retrieve the data from database table.
I have written a query if the user will select other values, it looks like this ,
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails where Date between '"
+ DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd")
+ "' and '"
+ DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd")
+ "' and Name ='"
+ DropDownList1.Text.ToString()
+ "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
Now the problem is I have to write query for AllRecords
.
try this:
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails ";
if ( DropDownList1.Text.ToString() != "AllRecords")
queryStr=queryStr+" where Date between '" + DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd") + "' and '" + DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd") + "'"+" and Name ='" + DropDownList1.Text.ToString() + "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
Only a small change in your query
You have to append and Name ='" + DropDownList1.Text.ToString() to the query only if its not AllRecords
Be care about SQL Injection. Use SQLParameter like this:
DataTable dt = new DataTable();
SqlDataAdapter s1 = new SqlDataAdapter();
s1.SelectCommand.Connection = conn;
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails WHERE Date BETWEEN @StartDate AND @EndDate";
s1.SelectCommand.Parameters.AddWithValue("StartDate", DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd"));
s1.SelectCommand.Parameters.AddWithValue("EndDate", DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd"));
if (DropDownList1.Text.ToString() != "AllRecords")
{
queryStr = queryStr + " AND Name = @Name";
s1.SelectCommand.Parameters.AddWithValue("Name", DropDownList1.Text.ToString());
}
s1.SelectCommand.CommandText = queryStr;
s1.Fill(dt);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.