Today, we will learn how we can assign a key value pair to a combo box. The value will be shown to the end user and on the basis of the value, you can get the key.
E.g.: Consider the following key, value pairs:
Key: 1, Value: Rohit
Key: 2, Value: Suraj
Now, the combo box will show the values to the end user as Rohit, Suraj and for the selected item, you can get the key as either 1 or 2.
It is a simple three step procedure and am explaining it with some code samples.
Step 1: Create a new public class, say, KeyValuePair as
public class KeyValuePair
{
public object m_objKey;
public string m_strValue;
public KeyValuePair(object NewKey,string NewValue)
{
m_objKey = NewKey;
m_strValue = NewValue;
}
public override string ToString()
{
return m_strValue;
}
}
Step 2: From your Main class, add the items to combo box as comboBox1.Items.Add(new KeyValuePair("1", "Rohit"));
comboBox1.Items.Add(new KeyValuePair("2", "Suraj"));
comboBox1.Items.Add(new KeyValuePair("3", "Sandeep"));
comboBox1.Items.Add(new KeyValuePair("4", "Jagdeep"));
comboBox1.SelectedIndex = 0;
Step 3: Now you can fetch the key-value pair as KeyValuePair objKeyValuePair = (KeyValuePair)comboBox1.SelectedItem;
string strkey = objKeyValuePair.m_objKey.ToString();
string strvalue = objKeyValuePair.m_strValue.ToString();
MessageBox.Show("Key: " + strkey + " || Value: " + strvalue);
That’s it. Put the code written in step 3 on some button click event, say button1Click_event. Now, whenever you will click the button, a message box will come that show you the Key and Value of the item which is currenlt selected in the combo box.If you find any kind of issue/query, please do let me know.
Haapy coding
-Rohit
No comments:
Post a Comment