2017-05-11 6 views
0

저는 프로그래밍의 초보자입니다. 첫 번째 문자로 직원 이름을 검색하고 예 : A에서 시작하는 이름을 모두 표시하려면 어떻게해야합니까? 그러면 데이터 그리드보기에 표시되어야합니까? 현재, 내 코드는 텍스트 상자에서 2 글자를 감지 한 다음 그리드보기로 표시합니다. 첫 글자를 찾아 내고 싶습니다. 당신은 단지 특정 텍스트의 첫 글자를 얻고 싶다면텍스트 상자의 첫 문자를 감지하면 gridview에 나타납니다.

private void textBoxName_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    con = new SqlConnection(cs); 
    con.Open(); 
    adapt = new SqlDataAdapter(
     "select name, empno, workno from m_employee where name like '%" + 
     textBoxName.Text + "%' and not [recsts] = 'R' order by empno", con); 
    dt = new DataTable(); 
    adapt.Fill(dt); 
    dataGridView1.DataSource = dt; 
    con.Close(); 

    if (textBoxName.Text != null) 
    { 
     dataGridView1.Visible = true; 
    } 

    if (textBoxName.Text == "") 
    { 
     dataGridView1.Visible = false; 
    } 

} 

private void textBoxName_TextChanged(object sender, EventArgs e) 
{ 
    textBoxName.Text = textBoxName.Text.TrimEnd(); 

    if (textBoxName.Text == "") 
    { 
     dataGridView1.Visible = false; 
    } 

    (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = 
     string.Format("Name LIKE '%{0}%'", textBoxName.Text); 
} 

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) 
    { 

      textBoxName.Text = dataGridView1.Rows[e.RowIndex].Cells["name"].Value.ToString(); 
      textBoxEmplNo.Text = dataGridView1.Rows[e.RowIndex].Cells["empno"].Value.ToString(); 
      textBoxWorkNo.Text = dataGridView1.Rows[e.RowIndex].Cells["workno"].Value.ToString(); 

     string selectSql = "select icnum, empno, passport, deptno, section from m_employee where [email protected]"; 
     SqlCommand cmd = new SqlCommand(selectSql, con); 
     cmd.Parameters.AddWithValue("@workno", textBoxWorkNo.Text); 

     bool isDataFound = false; 

     try 
     { 
      con.Open(); 

      using (SqlDataReader read = cmd.ExecuteReader()) 
      { 

       while (read.Read()) 
       { 
        isDataFound = true; 

        textBoxICPass.Text = (read["icnum"].ToString()); 
        textBoxPassport.Text = (read["passport"].ToString()); 
        textBoxDept.Text = (read["deptno"].ToString()); 
        textBoxSection.Text = (read["section"].ToString()); 

        string imgFilePath = @"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxEmplNo.Text + ".jpg"; 
        if (File.Exists(imgFilePath)) 
        { 
         pictureBox1.Visible = true; 
         pictureBox1.Image = Image.FromFile(imgFilePath); 
        } 
        else 
        { 
         // Display message that No such image found 
         // MessageBox.Show("No Image Found"); 
         pictureBox1.Visible = true; 
         pictureBox1.Image = Image.FromFile(@"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\No-image-found.jpg"); 
        } 


       } 
      } 
     } 
     finally 
     { 
      con.Close(); 
     } 


    } 
+0

오프 주제 중요하지만, 귀하의 코드가 SQL 인젝션에 취약 : 당신이 그으로부터 보호 유지해야하고 코드가 좀 더 읽기 쉽게 만들 수 있습니다 매개 변수화 된 쿼리를 사용하는 대신 고려하십시오. 매개 변수화 된 쿼리를 사용하십시오. –

+0

선행 공백을 원하지 않으면'TrimEnd' 대신'Trim'을 사용해야합니다. –

답변

0

것은, 이렇게하려면 다음 방법 중 하나를 수행 할 수 있습니다 :

// Access the first character by it's index 
var letter = YourTextBox.Text[0]; 

// Access the first letter via the Substring() method 
var letter = YourTextBox.Text.Substring(0, 1); 

오프 주제 여기 내 코드입니다 : 매개 변수화 된 쿼리 고려

은 쿼리 작성시 문자열 연결을 사용하면 안됩니다.

// Build your query using parameters 
var query = "SELECT ... WHERE Name LIKE @letter AND ..."; 

// Build your adapter to execute 
var adapter = new SqlDataAdapter(query, connection); 

// Add your parameter 
adapter.SelectCommand.Parameters.AddWithValue("@letter", letter + "%"); 

// Execute it here 
+0

코드는'private void textBoxName_KeyPress (object sender, KeyPressEventArgs e)'에 있어야합니다. ?? 미안하지만 아직 프로그래밍 과정을 배우고 있습니다. – Miza

+0

첫 번째 항목은 달성하려는 항목에 따라 실제로 적용될 수 있습니다 (예 : 변경된 내용을 쿼리하거나 업데이트 할 때 첫 번째 문자 만 포함하고 첫 번째 문자 만 저장). 사용되는 첫 번째 문자에만 관심이 있다면 ['TextBox.MaxLength'] (https://msdn.microsoft.com/en-us/library/system.windows.controls.textbox)를 설정하는 것이 좋습니다. maxlength (v = vs.110) .aspx) 속성을 사용하여 여분의 작업을하지 않아도되는 단일 문자 이상을 저장하지 않도록합니다. –

+0

나는 이미 시도했지만 작동하지 않습니다. 첫 글자를 입력하면 격자보기가 자동으로 나타납니다. 현재 두 개의 문자를 입력하면 그리드보기가 자동으로 나타납니다. – Miza

관련 문제