Guys I have a comboBox that is configured to work like dropdownlist. It is being populated through database. It is working flawlessly.
Now what I want to do is is this : For example I have comboBox that is getting "Names" column from database table "tblPersons" and displaying it. if, For example, there are total of 4 entries in database table "tblPersons"
So when I write "Ahmed Farooqi" in comboBox (comboBox should be editable and it should display all entries with name "Ahmed" once I have written "Ahmed") and press enter, it should search in database table "tblPersons" - if "Ahmed Farooqi" is found - it should select it, if "Ahmed Farooqi" is not found - it should ask if I want to create new entry in database table "tblPersons", if I click "yes" it should open another form for adding new person and if I click "No" it should do nothing.
How should I do this. I am new to C#, so any help would be greatly appreciated. I apologize if my question was unclear.
Regards.
Edit : This is my test form, here I a textBox that will be used to enter Name, the textbox should search for a name in database, then if name is found, display number and email from database in their respective textboxes. If not found, it should display messagebox asking user to create a new person and if clicked yes, switch to another form (where user will create new person).
call the fillCombo function in your form load and assign the cmb_SelectedValueChanged event to your combobox. Don't forget to set autocompletemode property to combobox.
cmb.AutoCompleteMode = AutoCompleteMode.SuggestAppend
private void fillCombo()
{
string sql = "SELECT ID, NAME, Number, Email FROM tblPerson";
SqlConnection Cnn = new SqlConnection("connections string");
Cnn.Open();
SqlDataAdapter da = new SqlDataAdapter(sql, Cnn);
DataTable dt = new DataTable();
da.Fill(dt);
cmb.ValueMember = "ID";
cmb.DisplayMember = "Name";
cmb.DataSource = dt;
}
private void cmb_SelectedValueChanged(object sender, EventArgs e)
{
if (cmb.SelectedItem != null)
{
txtNumber.Text = ((DataRow)cmb.SelectedItem)["Number"].ToString();
txtEmail.Text = ((DataRow)cmb.SelectedItem)["Email"].ToString();
}
}
private void cmb_Validating(object sender, CancelEventArgs e)
{
if (cmb.SelectedItem == null)
{
If (MessageBox.Show("Do you want to create a new person?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
frmNewPerson person = new frmNewPerson();
person.Name = cmb.Text;
if (person.ShowDialog() == DialogResult.Yes)
{
fillCombo();
DataRow dr = ((DataTable)cmb.DataSource).Select("Name='" + person.Name + "'")[0];
cmb.SelectedValue = Convert.ToInt32(dr["ID"]);
}
}
else
{
txtNumber.Text = string.Emtpy;
txtEmail.Text = string.Emtpy;
}
}
}
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.