ComboBox DisplayMember, ValueMember, and DataSource Method - c#

I am working on a c# winforms program that has three comboboxes, each combobox has a different displaymember, valuemember, and datasource. I would like to try to create a method in which I can use to set the member values and datasource that works for all three comboboxes
here is what I am currently using for the comboboxes
private void kitLoad (string kitDisplay, string kitValue, object kitSource)
{
kits_comboBox.DisplayMember = kitDisplay;
kits_comboBox.ValueMember = kitValue;
kits_comboBox.DataSource = kitSource;
}
private void pspLoad(string pspDisplay, string pspValue, object pspSource)
{
psp_comboBox.DisplayMember = pspDisplay;
psp_comboBox.ValueMember = pspValue;
psp_comboBox.DataSource = pspSource;
}
private void plateLoad(string plateDisplay, string plateValue, object plateSource)
{
plates_comboBox.DisplayMember = plateDisplay;
plates_comboBox.ValueMember = plateValue;
plates_comboBox.DataSource = plateSource;
}
It does work, But I feel like I could compress all of that into one method, any help is greatly appreciated.

just pass your combo along
private void LoadCombo(ComboBox cbo, string disp, string val, object data)
{
cbo.DisplayMember = disp;
cbo.ValueMember = val;
cbo.DataSource = data;
}
will work for any combo box
LoadCombo(kits_comboBox, "displayProperty", "valueProperty", data);

Related

unable select combobox value after form is loaded

cant select combo item by value after its passed to form. Comb is populated properly i get all the customers displayed by Text.
public OrderViewerForm(string orderId)
{
InitializeComponent();
PopulateCustomerCombobox();
PopulateForm(orderId);
PopulateProductsTable();
}
private void PopulateForm(string orderId)
{
OrderModel order = db.LoadOrder(orderId);
List<ProductsOrderedModel> productsOrdered = db.ProductsOrdered_Load(orderIdValue.Text);
orderIdValue.Text = order.Id.ToString();
customerIdValue.Text = order.CustomerId.ToString();
customerIdCombo.SelectedValue = order.CustomerId;
}
private void PopulateCustomerCombobox()
{
customerIdCombo.Items.Clear();
List<CustomerModel> customer = db.CustomerGet_All();
foreach (CustomerModel c in customer)
{
customerIdCombo.DisplayMember = "Text";
customerIdCombo.ValueMember = "Value";
customerIdCombo.Items.Add(new { Text = c.FullInfo, Value = c.Id });
}
}
At the end order.CustomerId is set properly but customerIdCombo.SelectedValue stays null. What am I doing wrong?
I would suggest switching to databinding here. Your foreach looks weird by the way.
private void PopulateCustomerCombobox()
{
customerIdCombo.DisplayMember = "Text";
customerIdCombo.ValueMember = "Value";
customerIdCombo.DataSource = db.CustomerGet_All().Select(c=> new { Text = c.FullInfo, Value = c.Id});
}
Thinking about it you may want to drop the hole anonymous type thing. why not simply bind the list you get from CustomerGet_All?

C# - How to set value to default from table in combobox datagridview?

How can you set default value for combobox provided you get the value from table in database. I am thinking comparing the value with column [2]/destinationColumn to see which value in the table should be selected as default. This is my code so far which is wrong. Suggestion or an example code will be much appreciated. Thank you in advance guys.
string sqlLookupColumn = "SELECT LookUpColumnID, SOURCE_NAME FROM TB_LOOKUP_COLUMN ORDER BY SOURCE_NAME ASC";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxColumn dgvCboColumn = new DataGridViewComboBoxColumn();
dgvCboColumn.Name = "DESTINATION_NAME";
dataGridView1.Columns.Add(dgvCboColumn);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewComboBoxCell cboDestinationColumns = (DataGridViewComboBoxCell)(row.Cells[3]);
cboDestinationColumns.DataSource = dsColumn.Tables[0];
string destinationColumn = row.Cells[2].Value.ToString();
cboDestinationColumns.DisplayMember = "SOURCE_NAME";
cboDestinationColumns.ValueMember = "LookUpColumnID";
if (destinationColumn == cboDestinationColumns.DisplayMember)
{
cboDestinationColumns.Selected = true;
}
}
Things that i can see wrong
1- Your loop on the GridView wont work, do the loop on the Dataset instead of the Gridview...
2- You are comparing destinationColumn with cboDestinationColumns.DisplayMember which = "SOURCE_NAME" and you want If destinationColumn = "InvoiceNo"
3- Add the to the combo items using for loop and .add method, and do your if statement their.
To add the items:
1st add this class
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
Then loop on the Dataset
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
DataRow dr = ds.Tables[0].Rows[i];
ComboboxItem tmp= new ComboboxItem();
tmp.Text = dr["SOURCE_NAME"];
tmp.Value = dr["LookUpColumnID"];
cb.Items.Add(tmp);
if(dr["InvoiceNo"].ToString() =="")//Your condition here to set selected
cb.SelectedIndex = i;
}

Extracting specific string from combobox select

I have a combobox for an item list that I populate using the following code:
List<string> comboboxItems = new List<string>();
foreach (var p in products)
{
var x = p.Product;
foreach (var pn in x)
{
comboboxItems.Add(pn.name + " :Qty " + pn.quantity_available
+ " :Tax " + pn.default_tax_tier);
}
}
cmbItems.DataSource = comboboxItems;
What should I do in order to get the value, pn.name only when the combobox item is selected?
Using WinForms.
You have to handle the event DataGridView.EditingControlShowing event, in there you can access the actual combobox and register the SelectedIndexChanged event handler like this:
//EditingControlShowing event handler for your dataGridView1
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e){
if(dataGridView1.CurrentCell.OwningColumn == cmbItems){
var combo = e.Control as ComboBox;
combo.SelectedIndexChanged -= cmbItems_SelectedIndexChanged;
combo.SelectedIndexChanged += cmbItems_SelectedIndexChanged;
}
}
private void cmbItems_SelectedIndexChanged(object sender, EventArgs e){
var combo = sender as ComboBox;
//Note that SelectedItem may be null
var s = Convert.ToString(combo.SelectedItem);
int i = s.IndexOf(" :Qty");
var selectedName = i == -1 ? "" : s.Substring(0,i+1).TrimEnd();
//other code ...
}
you should create an item such as
public class CboItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
then you can create easily using something like
CboItem item = new CboItem();
item.Text = "My Item";
item.Value = "Anything";
in the Value you can store your var pn whatever it is.
then you can retrieve like so :
((CboItem)comboBox1.SelectedItem).Value;
You will need to cast the result above to the proper type you stored inside as the Value is of type object.
We can also regular expressions to extract data from string.
Create string variable in the below format
string inputPattern = "{0} :Qty {1} :Tax {2}";
While inserting the data into combo box,
comboboxItems.Add(string.Format(inputPattern, p.Name, p.Quantity_Available, p.Tax));
After you added it, to extract the strings we can use Regex, code snippet below.
string extractPattern = "(?<Name>.*) :Qty (?<Qty>.*) :Tax (?<Tax>.*)";
foreach (var item in (comboBox1.DataSource as List<string>))
{
var matches = Regex.Match(item, extractPattern);
if (matches.Groups["Name"].Success)
{
MessageBox.Show(matches.Groups["Name"].Value);
}
if (matches.Groups["Qty"].Success)
{
MessageBox.Show(matches.Groups["Qty"].Value);
}
if (matches.Groups["Tax"].Success)
{
MessageBox.Show(matches.Groups["Tax"].Value);
}
}

How can I take all the elements / fields from a Listbox (in C#) and put them into a DataTable?

I have a win form which has a ListBox. I want to create dynamically a DataTable (till now I only declared some columns - you can see in the code - that I later want to use to link the DataTable to an existing empty DataBase) but don't know how to link it to the Listbox in order to "take" the 4 elements from it: event_time , event_filename , event_name , event_fullpath. Pls Help,
Part of my code till now is:
private delegate void AppendListHandler(string event_filename, String event_name, String event_fullpath);
private void AppendText(string event_filename, String event_name, String event_fullpath)
{
if (lstResultLog.InvokeRequired)
lstResultLog.Invoke(new AppendListHandler(AppendText), new object[] { event_filename, event_name, event_fullpath });
else
{
DateTime event_time = DateTime.Now;
//String event_duration = event_time.ToString("HH:mm");
lstResultLog.Items.Add(event_time + event_filename + event_name + event_fullpath);
}
DataTable table = new DataTable("tbl_Event");
table.Columns.Add("event_duration");
table.Columns.Add("event_name");
table.Columns.Add("event_filename");
table.Columns.Add("event_fullpath");
table = (DataTable)lstResultLog.DataSource;
}
lstResultLog is the name of the ListBox, all the fields from the ListBox have the exact name as in the declared DataTable, and as the DataBase.
You can have in your form a field of type DataTable that will hold the data you want. Then, whenever you add an item to your listbox, add a row to the data table with same data:
public class YourForm
{
private DataTable _table;
public YourForm()
{
InitializeComponents();
_table = BuildDataTable();
}
private DataTable BuildDataTable()
{
DataTable table = new DataTable("tbl_Event");
table.Columns.Add("event_duration");
table.Columns.Add("event_name");
table.Columns.Add("event_filename");
table.Columns.Add("event_fullpath");
return table;
}
private void AppendText(string event_filename, String event_name, String event_fullpath)
{
if (lstResultLog.InvokeRequired)
lstResultLog.Invoke(new AppendListHandler(AppendText), new object[] { event_filename, event_name, event_fullpath });
else
{
DateTime event_time = DateTime.Now;
lstResultLog.Items.Add(event_time + event_filename + event_name + event_fullpath);
//Create new row
var row = _table.NewRow();
// Fill row values
row["event_name"] = event_name;
// Add row to table
_table.Rows.Add(row);
}
}
}
And when you need to send the data to database, just send _table field as a parameter to the method that saves data.

ASP.NET: Listbox datasource and databind

I have an empty listbox on .aspx page
lstbx_confiredLevel1List
I am generating two lists programatically
List<String> l1ListText = new List<string>(); //holds the text
List<String> l1ListValue = new List<string>();//holds the value linked to the text
I want to load lstbx_confiredLevel1List list box on .aspx page with above values and text. So i am doing following:
lstbx_confiredLevel1List.DataSource = l1ListText;
lstbx_confiredLevel1List.DataTextField = l1ListText.ToString();
lstbx_confiredLevel1List.DataValueField = l1ListValue.ToString();
lstbx_confiredLevel1List.DataBind();
but it does not load the lstbx_confiredLevel1List with l1ListText and l1ListValue.
Any ideas?
Why don't you use the same collection as DataSource? It just needs to have two properties for the key and the value. You could f.e. use a Dictionary<string, string>:
var entries = new Dictionary<string, string>();
// fill it here
lstbx_confiredLevel1List.DataSource = entries;
lstbx_confiredLevel1List.DataTextField = "Value";
lstbx_confiredLevel1List.DataValueField = "Key";
lstbx_confiredLevel1List.DataBind();
You can also use an anonymous type or a custom class.
Assuming that you have already these lists and you need to use them as DataSource. You could create a Dictionary on the fly:
Dictionary<string, string> dataSource = l1ListText
.Zip(l1ListValue, (lText, lValue) => new { lText, lValue })
.ToDictionary(x => x.lValue, x => x.lText);
lstbx_confiredLevel1List.DataSource = dataSource;
You'd better used a dictionnary:
Dictionary<string, string> list = new Dictionary<string, string>();
...
lstbx_confiredLevel1List.DataSource = list;
lstbx_confiredLevel1List.DataTextField = "Value";
lstbx_confiredLevel1List.DataValueField = "Key";
lstbx_confiredLevel1List.DataBind();
Unfortunately the DataTextField and DataValueField are not used like that. They are the text representation of the fields they're supposed to show of the current item that's being databound in the DataSource.
If you had an object that held both text and value, you'd make a list of it and set that to datasource like this:
public class MyObject {
public string text;
public string value;
public MyObject(string text, string value) {
this.text = text;
this.value = value;
}
}
public class MyClass {
List<MyObject> objects;
public void OnLoad(object sender, EventArgs e) {
objects = new List<MyObjcet>();
//add objects
lstbx.DataSource = objects;
lstbx.DataTextField = "text";
lstbx.DataValueField = "value";
lstbx.DataBind();
}
}

Categories

Resources