c# combobox autocomplete set display text and value - c#

I need to create a combobox autocomplete which display text Name but when I click on text it gets value "ID" binding with "Name". I have already created a code but it is not working and I'm so confusing with set display text and value into combobox and autocomplete data-source binding.
private void loadAutoCompleteValues()
{
autoCompleteCombo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
autoCompleteCombo.AutoCompleteSource = AutoCompleteSource.CustomSource;
DataTable products;
con.MysqlQuery("select * from products");
products = con.QueryEx();
Dictionary<string, string> comboSource = new Dictionary<string, string>();
for (int i = 0; i < products.Rows.Count; i++)
{
DataRow dr = products.Rows[i];
comboSource.Add(dr["id"].ToString(), dr["name"].ToString());
}
autoCompleteCombo.DataSource = new BindingSource(comboSource, null);
autoCompleteCombo.DisplayMember = "Value";
autoCompleteCombo.ValueMember = "Key";
}
private void autoCompleteCombo_SelectedIndexChanged(object sender, EventArgs e)
{
string key = ((KeyValuePair<string, string>)autoCompleteCombo.SelectedItem).Key;
string value = ((KeyValuePair<string, string>)autoCompleteCombo.SelectedItem).Value;
MessageBox.Show(key + " " + value);
}

I may be incorrect here, however using your code I simply added the line autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems; to your code and it worked as expected.
autoCompleateCombo.DataSource = new BindingSource(comboSource, null);
autoCompleateCombo.DisplayMember = "Value";
autoCompleateCombo.ValueMember = "Key";
autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems; //<-- Added this line

Related

How to get value of ComboBox rather than text

I have a combobox cmbCourses and I am populating my this code
var _courses = new DatabaseHandler().GetAllCourses();
foreach (var a in _courses)
{
ComboBoxItem item = new ComboBoxItem();
item.Text = a.Value;
item.Value = a.Key;
cmbCourses.Items.Add(a.Value);
}
public Dictionary<int, String> GetAllCourses()
{
Dictionary<int, String> courses = new Dictionary<int, String>();
var connection = DatabaseConnector.Instance();
if(connection.IsConnect())
{
connection.Connection.Open();
string query = "SELECT * FROM courses";
cmd = new MySqlCommand(query, connection.Connection);
cmd.Prepare();
var result = cmd.ExecuteReader();
while(result.Read())
{
courses.Add(result.GetInt16(0), result.GetString(1));
}
}
connection.Connection.Close();
return courses;
}
But when I try to get key it shows value instead
using this code
MessageBox.Show(cmbCourses.SelectedItem.ToString());
You are only adding the value to the ComboBox. Add the KeyValuePair to the ComboBox and set the DisplayMemberPath and SelectedValuePath properties:
var _courses = new DatabaseHandler().GetAllCourses();
foreach (var a in _courses)
{
cmbCourses.Items.Add(a);
}
cmbCourses.DisplayMemberPath = "Value";
cmbCourses.SelectedValuePath = "Key";
You can then get the key of the selected item like this:
var item = cmbCourses.SelectedItem as KeyValuePair<int, String>;
if (item != null)
MessageBox.Show(item.Key);
You can use the GetValue() method to get the value rather than the display text:
MessageBox.Show(cmbCourses.GetValue().ToString());
Seems you have problem in adding items to your combobox, you are adding only the value by this line cmbCourses.Items.Add(a.Value);, Can you try this :
cmbCourses.Items.Add(item);
Then you can use this line to get the value :
MessageBox.Show(cmbCourses.SelectedValue.ToString());
Don't forget to set these for your combobox :
cmbCourses.DisplayMember = "YOUR DISPLAY FIELD NAME";
cmbCourses.ValueMember = "YOUR VALUE FIELD NAME";

Filling a DataGrid with selfmade arraylist

I'm making a generic converter which reads any file you throw in it which "maps" it's data and gives it like this:
I got 3 classes:
DataValue, which has a value, row, and column property.
DataArray, which is a list of DataValues.
DataArrayList, which is a list of DataArrays.
I try to use put it in a datagrid with non pre-setup columns, since it should be able to read Anything.
Here's some code:
public void FillRows(DataArrayList arrayList)
{
DataArray headers = arrayList.First();
AddColumns(headers);
DataList = new List<DataArray>();
lijstitems = new List<DataValue>();
foreach (DataArray dataArrays in arrayList)
{
DataList.Add(new DataArray { datavalues = dataArrays.datavalues });
}
DataContext = this;
}
Now this gives me the general name of the arrays, as a test i tried to display it in textboxes. Now i wonder how i would get a setup which displays each DataValue as a new column.
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataArray array = (DataArray)DataGrid.SelectedItem;
var arraychar = array.datavalues.ToArray();
textBox1.Text = arraychar[0].value.ToString();
textBox2.Text = arraychar[1].value.ToString();
textBox3.Text = arraychar[2].value.ToString();
textBox4.Text = arraychar[3].value.ToString();
textBox5.Text = arraychar[4].value.ToString();
}
This displays the correct values i put in.
Define a column per value you want to display in the DataGrid:
DataGrid.AutoGenerateColumns = false;
DataGrid.Columns.Add(new DataGridTextColumn() { Binding = new Binding("[0]") });
DataGrid.Columns.Add(new DataGridTextColumn() { Binding = new Binding("[1]") });
DataGrid.Columns.Add(new DataGridTextColumn() { Binding = new Binding("[2]") });
DataGrid.Columns.Add(new DataGridTextColumn() { Binding = new Binding("[3]") });
DataGrid.Columns.Add(new DataGridTextColumn() { Binding = new Binding("[4]") });

Dynamically added Dropdownlist's SelectedValue not working

I am creating combobox dynamically in winforms
ComboBox ddCntrl = new ComboBox();
ddCntrl.Width = 100;
ddCntrl.Name="dd_" + tpObj.RowColId;
ddCntrl.DropDownStyle = ComboBoxStyle.DropDownList;
Dictionary<int, string> DC = new Dictionary<int, string>();
DC[-1] = "N/A";
DC[0] = "Y";
DC[1] = "N";
ddCntrl.DataSource = new BindingSource(DC,null);
ddCntrl.DisplayMember = "Value";
ddCntrl.ValueMember = "Key";
ddCntrl.SelectedIndex = ddCntrl.Items.IndexOf("N");
TableLayoutPanel.Controls.Add(ddCntrl, 1, 1);
I tried couple of option to set the selected value nothing is working
I tried below options to set selected value
ddCntrl.SelectedValue ="N";
ddCntrl.SelectedIndex = ddCntrl.FindStringExact("N")
You will need to change some things. First, if you are using this code in the constructor, you will need to move it to Load or Shown event.
And set the index after add the comboBox to the panel. ddCntrl.FindStringExact("N") should works ok:
ComboBox ddCntrl = new ComboBox();
ddCntrl.Width = 100;
ddCntrl.Name = "dd_";
ddCntrl.DropDownStyle = ComboBoxStyle.DropDownList;
Dictionary<int, string> DC = new Dictionary<int, string>();
DC[-1] = "N/A";
DC[0] = "Y";
DC[1] = "N";
ddCntrl.DataSource = new BindingSource(DC, null);
ddCntrl.DisplayMember = "Value";
ddCntrl.ValueMember = "Key";
tableLayoutPanel.Controls.Add(ddCntrl, 1, 1);
ddCntrl.SelectedIndex = ddCntrl.FindStringExact("N");
Since you are binding to a Dictionary you should set selected item as follows:ddCntrl.SelectedItem = DC[1];
If you would like to set depending on display value (which i really do not suggest) you have to find it in DC and then set it to ddlCntrl

Setting DataPropertyName in DataGridViewComboBoxColumn from BindingSource

I have a problem with setting a correct data property for DataPropertyName of DataGridViewComboBoxColumn. I have a BindingSource and I set its DataSource to BindingList of custom objects. These objects have properties which I'd like to assign as columns in DataGridView (pluginsDataGrid):
var source = new BindingSource {DataSource = _plugins};
pluginsDataGrid.AutoGenerateColumns = false;
pluginsDataGrid.DataSource = source;
Everything's fine when I have a simple string as a property - it is Name:
using (var nameCol = new DataGridViewTextBoxColumn())
{
nameCol.DataPropertyName = "Name";
nameCol.Name = "Name";
pluginsDataGrid.Columns.Add(nameCol);
}
but I don't know how to set DataGridViewComboBoxColumn options. I gave it a try this way:
using (var depCol = new DataGridViewComboBoxColumn())
{
depCol.DataPropertyName = "Dependencies";
depCol.Name = "Dependencies";
pluginsDataGrid.Columns.Add(depCol);
}
where Dependencies is a list of strings. But it is not working. What kind of property should be assign to it?
You need to specify DataSource for the column, example:
comboboxColumn.DataSource = collection;
comboboxColumn.ValueMember = ColumnName;
comboboxColumn.DisplayMember = ValueMember;
In your case use DataBindingComplete event to psecify collection:
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells["Dependencies"];
[Plugin_Type] entry = dataGridView1.Rows[i].DataBoundItem as [Plugin_Type];
comboCell.DataSource = entry.[YOUR_PROPERTY];
}
}

populate dropdownlist from hashtable

I'm trying to fill a dropdownlist from a Hashtable, the HashTable keys & values pulled from database, private Hashtable myHashTable = new Hashtable();
using the following method:
void LoadmyHashTable()
{
bussinessObject bs = new bussinessObject();
myDataset ds = new myDataset();
ds = bs.GetPosType(-1);
int rowsCount = ds.myTable.Rows.Count;
for (int i = 0; i < rowsCount; i++)
{
myHashTable.Add(ds.myTable.Rows[i]["dTypeName"],ds.myTable.Rows[i]["dTypeId"] );
}
}
then, after call the method in page load() and trying to fill the dropdownlist with the hashTable values:
myDropdownlist.DataSource = myHashTable;
myDropdownlist.DataTextField = "key";
myDropdownlist.DataValueField = "value";
myDropdownlist.DataBind();
The problem my dropdownlist appear with empty!
Thanks in advance.
ASP.NET,C#
I have modify code as below please try it.
void LoadmyHashTable()
{
bussinessObject bs = new bussinessObject();
DataSet ds = new DataSet();
ds = bs.GetPosType(-1);
if (ds.Tables.Count > 0 )
{
for (int i = 0; i < ds.Tables[0].Rows.Count-1; i++)
{
myHashTable.Add(ds.Tables[0].Rows[i]["dTypeId"], ds.Tables[0].Rows[i]["dTypeName"]);
}
}
}
use code for page load as below
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadmyHashTable();
if (myHashTable.Count > 0)
{
myDropdownlist.DataSource = myHashTable;
myDropdownlist.DataTextField = "Value";
myDropdownlist.DataValueField = "Key";
myDropdownlist.DataBind();
}
}
}
Hope this will helps you...happy coding...
The DataTextField and DataValueField values need to each correspond to a property in the binding source. Your code assumes a collection of objects that have at minimum a property named "key" and another named "value". Since this is not true, no items get bound.
EDIT: This code hasn't been tested at all, but you should be able to use LINQ to project your dataset into an anonymous collection:
var myHashTable = ds.myTable.Rows.Select( row => new { key = row["dTypeName"], value = row["dTypeId"] } );
Then the binding you are using should work.

Categories

Resources