1

我有三个文本框和一个下拉菜单,如下图所示。现在在提交按钮上单击我必须通过应用 if-else 块来检查 16 个案例。以下是我当前使用的代码:

在此处输入图像描述

protected void btnsearch_Click(object sender, EventArgs e)
{
    DateTime date = System.DateTime.Today;
    string strdate = date.ToString("dd-MM-yy");

    //Response.Write("class=" + drpclass.SelectedIndex + "tchrname=" + txt_tchrname.Text + "studentcode=" + txt_studentcode.Text + "date=" + strDTentered1);

    if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length == 0)
    {
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'";
        lbl_norecord.Visible = false;
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length == 0)
    {
        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";

        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "' and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "'";
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length == 0)
    {

        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "' and tblhomework.StudentsCode like'" + studentcode + "'";
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length != 0)
    {
        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'";
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length == 0)
    {

        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "' and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'";
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length == 0)
    {

        //            lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "' and tblhomework.StudentsCode like'" + studentcode + "'";
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length != 0)
    {
        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");

        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'";
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length == 0)
    {

        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";

        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "' and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "' and tblhomework.StudentsCode like'" + studentcode + "'";
        goto RC_sql;
    }

    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length != 0)
    {
        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";

        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "' and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "'";
        goto RC_sql;
    }
    else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length != 0)
    {
        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "' and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "' and tblhomework.StudentsCode like'" + studentcode + "'";

        goto RC_sql;
    }
    else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length != 0)
    {
        // lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'  and tblhomework.StudentsCode like'" + studentcode + "'";
        goto RC_sql;

    }
    else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length == 0)
    {
        //  lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "'  and tblhomework.StudentsCode like'" + studentcode + "' and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "'";

        goto RC_sql;
    }
    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length == 0)
    {

        // lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate + "'  and tblhomework.StudentsCode like'" + studentcode + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'";
        goto RC_sql;

    }
    else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length != 0)
    {
        // lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'  and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "'";
        goto RC_sql;

    }
    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length != 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length != 0)
    {
        //lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'  and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "' and tblhomework.StudentsCode like'" + studentcode + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'";
        goto RC_sql;

    }
    else if (drpclass.SelectedIndex != 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length != 0 && txtdatesearch.Text.Length != 0)
    {
        // lbl_norecord.Visible = false;
        classnorecord.Visible = false;
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        //DateTime  = CalendarExtender1.SelectedDate.Value;
        string strDTentered1 = DTentered1.ToString("dd-MM-yy");
        string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
        strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'  and  tblhomework.StudentsCode like'" + studentcode + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'";
        goto RC_sql;

    }
    //else if (drpclass.SelectedIndex == 0 && txt_tchrname.Text.Length == 0 && txt_studentcode.Text.Length == 0 && txtdatesearch.Text.Length == 0)
    //{

    //    //DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
    //    ////DateTime  = CalendarExtender1.SelectedDate.Value;
    //    //string strDTentered1 = DTentered1.ToString("dd-MM-yy");
    //    //string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
    //    //strwhere = " DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'  and  tblhomework.StudentsCode like'" + studentcode + "' and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'";
    //    Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script language=JavaScript>alert('Please fill atleast one field ');</script>");

    //}
    else
    //{
    //    lbl_norecord.Text = "Please fill atleast one Field";
    //    lbl_norecord.Visible = true;
    {
        classalert.Visible = true;
        classnorecord.Visible = false;
        classnorecordtoday.Visible = false;
        grdhomework.Visible = false;
        goto RC_EXIT;

    }

RC_sql:
    sqlsearch = "SELECT tblhomework.ID,tblteacher.TEACHERNAME,tblclass.CLASSNAME,tblhomework.Title,tblhomework.HomeworkDetail,tblhomework.StudentsCode FROM tblhomework" +
        " join tblclass on tblclass.CLASSCODE=tblhomework.ClassCode join tblteacher on tblteacher.TSHORTNAME=tblhomework.Tshortcode where " + strwhere;
    ds = obj.openDataset(sqlsearch, Session["SCHOOLCODE"].ToString());

    if (ds.Tables[0].Rows.Count == 0)
    {
        //lbl_norecord.Text = "Record Not Found";
        //lbl_norecord.Visible = true; grdhomework.Visible = false;
        classnorecord.Visible = true;
        classnorecordtoday.Visible = false;
        classalert.Visible = false;
    }
    else
    {
        grdhomework.Visible = true;
        grdhomework.DataSource = ds;
        grdhomework.DataBind();
        blankdata();
        classnorecord.Visible = false;
        classnorecordtoday.Visible = false;
        classalert.Visible = false;
    }
RC_EXIT:
    Response.Write("");
} 

现在我想要某种方式,我不必制作太多 if else 条件。因为 if-else 条件随着文本框数量的增加而增加。

4

3 回答 3

0

您可以按以下方式编写:

String drpClassString = ""

If(drpclass.SelectedIndex != 0)
{
  drpString = " and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'"
}
String thrNameString = "";
if(txt_tchrname.Text.Length != 0)
{
thrNameString = " and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "'"
}
String dateString = ""
if( txtdatesearch.Text.Length != 0)
{
dateString =" and DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'"
}


String sqlsearch = "SELECT tblhomework.ID,tblteacher.TEACHERNAME,tblclass.CLASSNAME,tblhomework.Title,tblhomework.HomeworkDetail,tblhomework.StudentsCode FROM tblhomework" +
        " join tblclass on tblclass.CLASSCODE=tblhomework.ClassCode join tblteacher on tblteacher.TSHORTNAME=tblhomework.Tshortcode where 1 = 1" + drpClassString + thrNameString +dateString;

希望这可以帮助。

于 2013-11-14T11:43:19.257 回答
0

使用StringBuilder创建string搜索。

更好的方法是使用字符串生成器

StringBuilder sb=new StringBuilder();
DateTime date = System.DateTime.Today;
String strdate = date.ToString("dd-MM-yy");
sb.append(" DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strdate);

if(drpclass.SelectedIndex != 0)
{
//sb.append("ClassName='"+ drpclass.SelectedValue.Text + "'")
}
if(string.isEmptyorNull(txtTecher.Text))
{
//sb.append("TeacherName='" +txtTecher.Text+"'")
}
//write other condition 
//Sql Query="select * from  where"+sb.toString();
于 2013-11-14T11:52:33.900 回答
0

实现这一点(在实践中)的最佳方法是重新编写查询,以便:

  1. 它不依赖于值。
  2. 如果存在这些值,则将它们参数化以避免SQL 注入(使用System.Data.Odbc是因为您使用的是 MySQL)。

以下是编写查询的一种方法:

SELECT  tblhomework.ID
        , tblteacher.TEACHERNAME
        , tblclass.CLASSNAME
        , tblhomework.Title
        , tblhomework.HomeworkDetail
        , tblhomework.StudentsCode
FROM    tblhomework
        JOIN tblclass
            ON  tblclass.CLASSCODE = tblhomework.ClassCode
        JOIN tblteacher
            ON  tblteacher.TSHORTNAME = tblhomework.Tshortcode
WHERE   (tblhomework.ClassCode = @dropClass OR @dropClass IS NULL)           -- effectively ignores this portion of WHERE clause if @dropClass IS NULL
        AND (tblhomework.TshortCode = @teacherName OR @teacherName IS NULL)  -- effectively ignores this portion of WHERE clause if @teacherName IS NULL
        AND (tblhomework.StudentsCode LIKE @studentCode)                     -- ternary operator in code-behind sets to wildcarded actual value or just a wildcard
        AND (DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y') = @dateEntered) -- if condition in code-behind sets to current date or custom date

然后在您的代码隐藏中,您可以编写if条件(一次)来设置每个单独的参数:

protected void btnsearch_Click(object sender, System.EventArgs e)
{
    // define relevant date
    string strDate = string.Empty;
    if (txtdatesearch.Text.Length != 0) { // one "if condition" to determine which date to use
        DateTime DTentered1 = DateTime.ParseExact(txtdatesearch.Text, CalendarExtender1.Format, null);
        strDate = DTentered1.ToString("dd-MM-yy");
    } else {
        strDate = System.DateTime.Today.ToString("dd-MM-yy");
    }
    // define query
    string query = "SELECT tblhomework.ID, tblteacher.TEACHERNAME, tblclass.CLASSNAME, tblhomework.Title, tblhomework.HomeworkDetail, tblhomework.StudentsCode FROM tblhomework JOIN tblclass ON tblclass.CLASSCODE = tblhomework.ClassCode JOIN tblteacher ON tblteacher.TSHORTNAME = tblhomework.Tshortcode WHERE (tblhomework.ClassCode = @dropClass OR @dropClass IS NULL) AND (tblhomework.TshortCode = @teacherName OR @teacherName IS NULL) AND (tblhomework.StudentsCode LIKE @studentCode) AND (DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y') = @dateEntered)";
    // define connection string
    OdbcConnection conn = new OdbcConnection(YourConnectionStringGoesHere);
    OdbcCommand cmd = null;
    // define command
    using (OdbcCommand cmd = new OdbcCommand(query, conn)) {
        // add parameters using the ternary operator (?:) to handle cases that are not the date.
        // The ternary operator works like an inline "if (condition) {this} else {that}"
        // It's written in the form of "condition ? this : that;"
        cmd.Parameters.Add("dropClass", OdbcType.Int).Value = (drpclass.SelectedIndex != 0 ? drpclass.SelectedItem.Value : System.DBNull.Value);
        cmd.Parameters.Add("teacherName", OdbcType.VarChar, 50).Value = (txt_tchrname.Text.Length != 0 ? txt_tchrname.Text.ToString() : System.DBNull.Value);
        cmd.Parameters.Add("studentCode", OdbcType.VarChar, 50).Value = (txt_studentcode.Text.Length != 0 ? "%" + txt_studentcode.Text.ToString() + "%" : "%");
        cmd.Parameters.Add("dateEntered", OdbcType.VarChar, 50).Value = strDate;

        conn.Open();
        // you're using a dataset, and the OdbcCommand returns a reader
        // see the function defined below for ConvertDataReaderToDataSet
        DataSet(ds == ConvertDataReaderToDataSet(cmd.ExecuteReader()));
        // I'm not familiar with the openDataset(String, String) function, and I'm not sure what "obj" is...
        // Is this supposed to cache the result in session?
        // ds = obj.openDataset(sqlsearch, Session["SCHOOLCODE"].ToString());
    }

    if ((ds.Tables(0).Rows.Count == 0)) {
        //lbl_norecord.Text = "Record Not Found";
        //lbl_norecord.Visible = True
        grdhomework.Visible = false;
        classnorecord.Visible = true;
        classnorecordtoday.Visible = false;
        classalert.Visible = false;
        Response.Write("");
    } else {
        grdhomework.Visible = true;
        grdhomework.DataSource = ds;
        grdhomework.DataBind();
        blankdata();
        classnorecord.Visible = false;
        classnorecordtoday.Visible = false;
        classalert.Visible = false;
    }
}
// function ConvertDataReaderToDataSet by Mohammed Fauzi, found at http://mohammedfauzi.blogspot.com/2009/12/convert-datareader-to-dataset-through-c.html
public DataSet ConvertDataReaderToDataSet(System.Data.Odbc.OdbcDataReader reader)
{
    DataSet dataSet = new DataSet();
    do {
        // Create data table in runtime
        DataTable schemaTable = reader.GetSchemaTable();
        DataTable dataTable = new DataTable();
        if (schemaTable != null) {
            for (int i = 0; i < schemaTable.Rows.Count; i++) {
                DataRow dataRow = schemaTable.Rows[i];
                // Create a column name as provided in Schema
                string columnName = (string)dataRow["ColumnName"];
                // Define Column Type here
                DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
                //Adding Column to table
                dataTable.Columns.Add(column);
            }
            dataSet.Tables.Add(dataTable);
            // Fill the data table from reader data
            while (reader.Read()) {
                DataRow dataRow = dataTable.NewRow();
                for (int i = 0; i < reader.FieldCount; i++) {
                    dataRow[i] = reader.GetValue(i);
                }
                dataTable.Rows.Add(dataRow);
            }
        } else {
            // No records were returned
            DataColumn column = new DataColumn("RowsAffected");
            dataTable.Columns.Add(column);
            dataSet.Tables.Add(dataTable);
            DataRow dataRow = dataTable.NewRow();
            dataRow[0] = reader.RecordsAffected;
            dataTable.Rows.Add(dataRow);
        }
    } while (reader.NextResult());
    return dataSet;
}

对于这个答案的延迟,我深表歉意。当我准备好它时,你已经接受了另一个答案。但是,出于良心,我不能在不提及您的原始帖子中固有的SQL 注入的危险以及在已接受的答案中未提及的情况下就发布此帖子。

考虑一下如果您的用户输入'; DROP TABLE tblhomework;for会发生什么txt_tchrname.Text

thrNameString = " and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "'"

因为您没有使用参数化值,所以您的查询现在变为:

SELECT  tblhomework.ID
        , tblteacher.TEACHERNAME
        , tblclass.CLASSNAME
        , tblhomework.Title
        , tblhomework.HomeworkDetail
        , tblhomework.StudentsCode
FROM    tblhomework
        JOIN tblclass
            ON  tblclass.CLASSCODE = tblhomework.ClassCode
        JOIN tblteacher
            ON  tblteacher.TSHORTNAME = tblhomework.Tshortcode
WHERE   1 = 1
        AND tblhomework.TshortCode = ''; DROP TABLE tblhomework';

并立即删除您的主表。

当您使用参数化变量时,它们被评估为一种类型而不是潜在的 SQL 片段,因此不会将可执行的 SQL 注入到您的语句中。

听从Little Bobby Tables的教训。

请。

您的用户会感谢您。

于 2013-11-15T13:00:14.343 回答