본문 바로가기
개발언어/C#.NET

C# TextBox AutoCompleted 자동완성

by 엔돌슨 2009. 3. 5.
반응형
C# TextBox AutoCompleted 자동완성



참고블로그
http://csharpdotnetfreak.blogspot.com/2009/01/winforms-autocomplete-textbox-using-c.html



방법2는 디비에서 가져와서 세팅하는 방법입니다
2. AutoComplete textBox by fetching the data from database.

For this i've created a database with a table containing names which will be shown in textbox as suggestions, for this we need to create a AutoCompleteStringCollection and then add the records in this collection using datareader to fetch records from database

For autocomplete functionalty to work we need to define these 3 properties of textbox

1. AutoCompleteMode - we can choose either suggest or appned or suggestappend as names are self explanatory

2. AutoCompleteSource - this needs to be set as Custom Source

3. AutoCompleteCustomSource - this is the collection we created earlier

The complete C# code will look like this

namespace AutoCompleteTextBox
{

public partial class frmAuto : Form
{
public string strConnection =
ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection =
new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}

private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"Select distinct [Name] from [Names]" +
" order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());

}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();

txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;

}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show("Hope you like this example");
}

}
}


In the similar way we can also create a autocomplete type combobox



코드프로젝트에서 참고할만한 자료
http://www.codeproject.com/KB/miscctrl/WinAutoComplete.aspx

상세한 설명과 그림 ㄷㄷㄷ

여기도 좋은자료 (동일)
http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
다운로드 하려면 회원가입을 해야한다



이건 간단히 AutoCompleteStringCollection 를 쓰지 않고 사용하는 방법

http://www.devasp.net/net/articles/display/730.html