This is a little piece of code I wrote to autocomplete my textbox from the database as I type:
{
SqlConnection connString = new SqlConnection();
connString.ConnectionString = "Data Source=************************;Initial Catalog=STUPELG;Persist Security Info=True;User ID=****************;Password=**********";
SqlDataAdapter adapter = new SqlDataAdapter();
connString.Open();
SqlDataReader dataReader;
SqlCommand command = new SqlCommand("SELECT Name FROM dbo.Entity WHERE Name LIKE @name", connString);
command.Parameters.Add(new SqlParameter("@name", "%" + tbEntity.Text + "%"));
command.ExecuteNonQuery();
dataReader = command.ExecuteReader();
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
while (dataReader.Read())
{
col.Add(dataReader.GetString(0));
}
tbEntity.AutoCompleteCustomSource = col;
connString.Close();
}
However, I want to display two fields (EntityID, Name) out of the database into the textbox, but
Any suggestions?
Usually a textbox is not used to display more than one data coming from the database. But also notice that autocomplete is a tool to help your end users to choose while typing.
If you want to add also the EntityID you need to add it after the name in the autocomplete source.
First you need to change the sql command to retrieve also the EntityID field and not just the Name field
string cmdText = "SELECT Name, EntityID FROM dbo.Entity WHERE Name LIKE @name";
SqlCommand command = new SqlCommand(cmdText, connString);
Then inside the loop that read the values you add both the Name and the EntityID as part of the string added to the autocomplete collection
while (dataReader.Read())
{
string data = $"{dataReader.GetString(0)} {dataReader.GetInt32(1)}"
col.Add(data);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.