【问题标题】:How to display records by matching the text in a textbox?如何通过匹配文本框中的文本来显示记录?
【发布时间】:2014-02-10 23:31:30
【问题描述】:

我有两张表,即预约表和医疗中心,它们使用 mcID 相互关联。现在我的预约表格,我使用外连接在医疗中心表中显示 mcCentre,而不是在 gridview 中显示 mcID。您在我的表格中看到,所有医疗中心(mcCentre)都显示在网格视图中。但我只想显示黄和梁家庭诊所的记录,因为我想匹配文本框中的文本,即黄和梁家庭诊所。这意味着水医院文本在文本框中,我只希望该医院记录出现在网格视图中。文本框名称为 txtCentre。

 private void LoadAppointmentRecords()
{

    //retrieve connection information info from App.config
    string strConnectionString = ConfigurationManager.ConnectionStrings["SACPConnection"].ConnectionString;
    //STEP 1: Create connection
    SqlConnection myConnect = new SqlConnection(strConnectionString);
    //STEP 2: Create command
    //string strCommandText = "SELECT appointmentID, convert(varchar, aDate, 103) AS aDate, aTime, aStatus, aContact, aHeight, aWeight, patientID, mcID, nurseID FROM APPOINTMENT";

    string strCommandText = "SELECT appointmentID, convert(varchar, aDate, 103) AS aDate, aTime, aStatus, aContact, aHeight, aWeight, pat.pFirstName, pat.pLastName, cen.mcCentre, nur.nUsername FROM APPOINTMENT AS app";
    strCommandText += " LEFT OUTER JOIN PATIENT as pat on app.patientid = pat.patientid";
    strCommandText += " LEFT OUTER JOIN MEDICALCENTRE as cen on app.mcid = cen.mcid";
    strCommandText += " LEFT OUTER JOIN NURSE as nur on app.nurseid = nur.nurseid";
    //strCommandText += " LEFT OUTER JOIN NURSE as nur on app.nurseid = nur.nurseid";

    AppointmentAdapter = new SqlDataAdapter(strCommandText, myConnect);

    //command builder generates Select, update, delete and insert SQL
    // statements for MedicalCentreAdapter
    //SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(AppointmentAdapter);
    // Empty Employee Table first
    Appointment.Clear();
    // Fill Employee Table with data retrieved by data adapter
    // using SELECT statement
    AppointmentAdapter.Fill(Appointment);

    // if there are records, bind to Grid view & display
    if (Appointment.Rows.Count > 0)
        grdApp.DataSource = Appointment;
}

【问题讨论】:

    标签: c# windows datagridview textbox record


    【解决方案1】:

    将此代码添加到您的字符串...这将匹配 txtCentre.Text 中的任何内容,即使文本尚未完全输入,只需匹配几个字符或单词即可。

     strCommandText += " WHERE mcCentre like '%" + txtCentre.Text.Replace("'", "''").Trim() + "%'";
    

    这将完全匹配 txtCentre.Text 中的任何内容...

    strCommandText += " WHERE mcCentre like '" + txtCentre.Text.Replace("'", "''").Trim() + "'";
    

    将 .Replace("'", "''").Trim() 添加到您的 Text 应该可以帮助您避免不使用参数的 SQL 注入,但是如果您想使用参数,您可以按照 Jon Barker 的方法 :)

    【讨论】:

      【解决方案2】:

      请记住,使用此方法会使您自己暴露于SQL injection 攻击。我建议使用 ORM,例如实体框架。如果您仍想使用 chris_techno25 发布的直接 SQL,则始终使用参数,而不是直接嵌入来自用户的字符串,未经处理。

      http://www.dotnetperls.com/sqlparameter

      【讨论】:

        猜你喜欢
        • 2010-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-09
        • 1970-01-01
        相关资源
        最近更新 更多