根据条件搜索数据

时间:2013-11-14 11:20:51

标签: c# mysql asp.net search if-statement

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

enter image description here

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条件增加,因为没有文本框增加。

3 个答案:

答案 0 :(得分: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;

希望这会有所帮助。

答案 1 :(得分:0)

使用StringBuilder为搜索创建string

更好的是使用STRING BUILDER

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

答案 2 :(得分:0)

实现此目的的最佳方法(在实践中)是重写您的查询,以便:

  1. 它不依赖于值。
  2. 如果值存在,则将其参数化以避免SQL Injection(使用System.Data.Odbc,因为您正在使用MySQL)。
  3. 以下是编写查询的一种方法:

    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 Injection的危险,而不是在接受的答案中解决。

    请考虑一下,如果您的用户为'; DROP TABLE tblhomework;输入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的教训。

    您的用户会感谢您。