0

我在 UI 中有这三列。在下拉列表中,我有一个AllRecords和其他一些字段。我选择该AllRecords字段并输入开始和结束日期的详细信息。

现在我写了一个查询来检索值。

当他选择时AllRecords,根据开始和结束日期,它必须显示或从数据库表中检索数据。

我已经写了一个查询,如果用户会选择其他值,它看起来像这样,

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);

现在的问题是我必须为AllRecords.

4

2 回答 2

0

尝试这个:

 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);

您的查询只有很小的变化

仅当查询不是AllRecords时,您必须将Name ='" + DropDownList1.Text.ToString()附加到查询中

于 2012-08-02T10:49:53.363 回答
0

注意 SQL 注入。像这样使用 SQLParameter:

    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);
于 2012-08-02T12:25:01.970 回答