I have a ComboBox
in a form and while the user typing some text in the box, if there are matching items in the database with the text typed, should be listed in the ComboBox
. So that the user can be notified if the item being entered is already in the database. I'm trying to achieve this as follows.
When a text is entered in the combo
it will fire an event. Listening to that event, Presenter
will get matching user list from the database and then the list will be set as the DataSource
of the ComboBox
as follows...
But why it is not displayed in the combo? Please let me know the issue in this code!
Form
public partial class frmUser : Form
{
// two seperate get and set properties are used to same combo box as a list will be set as the datasource.
public string UserName
{
get{return cmbUserName.Text;}
}
public IEnumerable<User> UserList
{
set { cmbUserName.DataSource = value; }
}
private void cmbUserName_TextChanged(object sender, EventArgs e)
{
OnChangeText(sender, e);
}
}
Presenter
class UserPresenter
{
private void WireUpEvents()
{
_View.OnChangeText += new EventHandler(_View_OnChangeText);
}
private void _View_OnChangeText(object sender, EventArgs e)
{
ShowMatchingUsers();
}
private void ShowMatchingUsers()
{
var userList = _DataService.GetUsers(_View.UserName ); //edit
_Veiew.UserList = userList; //edit
}
}
DataService
public IEnumerable<User> GetUsers(string userID)
{
string selectStatement = "SELECT user_id from [user] WHERE user_id like '@userID %'";
List<User> UserList = new List<User>();
using (var sqlConnection = new SqlConnection(db.ConnectionString))
using (var sqlCommand = new SqlCommand(selectStatement, sqlConnection))
{
sqlCommand.Parameters.Add("@userID", SqlDbType.VarChar).Value = userID ;
sqlConnection.Open();
using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
while (dataReader.Read())
{
UserList.Add(
new User
{
UserID = (string) dataReader["user_id"]
});
}
return UserList;
}
}