如何通过匹配文本框中的文本来显示记录?

时间:2014-02-10 23:31:30

标签: c# windows datagridview textbox record

我有两个表,即使用mcID彼此关系的约会表和医疗中心。现在我的约会表单,我使用外连接在gridcentre表中显示mcCentre而不是gridview中的mcID。你看我的表格,所有医疗中心(mcCentre)都显示在gridview中。但我只想显示Hwang和Liang Family Clinic的记录,因为我希望匹配Hwang和Liang Family Clinic文本框中的文本。这意味着沃特福医院文本在文本框中,我希望医院记录出现在gridview中。文本框名称为txtCentre。

enter image description here

enter image description here

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

2 个答案:

答案 0 :(得分: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的方法:)< / p>

答案 1 :(得分:0)

请记住,您使用此方法会让自己暴露于SQL injection次攻击。我建议使用ORM,例如实体框架。如果您仍希望使用直接SQL作为chris_techno25发布,那么总是使用参数,而不是直接嵌入来自用户的字符串,未经过清理。

http://www.dotnetperls.com/sqlparameter