저는 프로그래밍의 초보자입니다. 첫 번째 문자로 직원 이름을 검색하고 예 : 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();
}
}
오프 주제 중요하지만, 귀하의 코드가 SQL 인젝션에 취약 : 당신이 그으로부터 보호 유지해야하고 코드가 좀 더 읽기 쉽게 만들 수 있습니다 매개 변수화 된 쿼리를 사용하는 대신 고려하십시오. 매개 변수화 된 쿼리를 사용하십시오. –
선행 공백을 원하지 않으면'TrimEnd' 대신'Trim'을 사용해야합니다. –