how to set SelectedIndex in DataGridViewComboBoxColumn? - c#

i am using a datagridview in that i am using a datagridviewcomboboxcolumn, comboboxcolumn is displaying text but the problem is i want to select the first item of comboboxcolumn by default how can i do this
DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
i++;
}

The values available in the combobox can be accessed via items property
row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];

the best way to set the value of a datagridViewComboBoxCell is:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as
DataRowView).Row[1].ToString();
}
It worked with me very well

If I had known about doing it in this event, it would have saved me days of digging and
trial and errors trying to get it to set to the correct index inside the CellEnter event.
Setting the index of the DataGridViewComboBox is the solution I have been looking for.....THANKS!!!
In reviewing all the issues other coders have been experiencing with trying to set
the index inside of a DataGridViewComboBoxCell and also after looking over your code,
all that anyone really needs is:
1. Establish the event method to be used for the "EditingControlShowing" event.
2. Define the method whereby it will:
a. Cast the event control to a ComboBox.
b. set the "SelectedIndex" to the value you want.
In this example I simply set it to "0", but you'd probably want to apply so real life logic here.
Here's the code I used:
private void InitEvents()
{
dgv4.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( dgv4EditingControlShowing );
}
private void dgv4EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
{
ComboBox ocmb = e.Control as ComboBox;
if ( ocmb != null )
{
ocmb.SelectedIndex = 0;
}
}

If DataGridViewComboBoxCell already exist:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item 1", "0");
dt.Rows.Add("Item 2", "1");
dt.Rows.Add("Item 3", "2");
dt.Rows.Add("Item 4", "3");
for (int i = 0; i < dvg.Rows.Count; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dvg.Rows[i].Cells[1];
comboCell.DisplayMember = "Item";
comboCell.ValueMember = "Value";
comboCell.DataSource = dt;
};

I've had some real trouble with ComboBoxes in DataGridViews and did not find an elegant way to select the first value. However, here is what I ended up with:
public static void InitDGVComboBoxColumn<T>(DataGridViewComboBoxCell cbx, List<T> dataSource, String displayMember, String valueMember)
{
cbx.DisplayMember = displayMember;
cbx.ValueMember = valueMember;
cbx.DataSource = dataSource;
if (cbx.Value == null)
{
if(dataSource.Count > 0)
{
T m = (T)cbx.Items[0];
FieldInfo fi = m.GetType().GetField(valueMember, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
cbx.Value = fi.GetValue(m);
}
}
}
It basically sets the .Display and .ValueMember properties of the DataGridViewComboBoxCell and uses a List as DataSource. It then takes the first item, and uses reflection to get the value of the member that was used as ValueMember and sets the selected value via .Value
Use it like this:
public class Customer
{
private String name;
public String Name
{
get {return this.name; }
set {this.name = value; }
}
private int id;
public int Id
{
get {return this.id; }
set {this.id = value; }
}
}
public class CustomerCbx
{
private String display;
public String Display
{
get {return this.display; }
set {this.display = value; }
}
private Customer value;
public Customer Value
{
get {return this.value; }
set {this.value = value; }
}
}
public class Form{
private void Form_OnLoad(object sender, EventArgs e)
{
//init first row in the dgv
if (this.dgv.RowCount > 0)
{
DataGridViewRow row = this.dgv.Rows[0];
DataGridViewComboBoxCell cbx = (DataGridViewComboBoxCell)row.Cells[0];
Customer c1 = new Customer(){ Name = "Max Muster", ID=1 };
Customer c2 = new Customer(){ Name = "Peter Parker", ID=2 };
List<CustomerCbx> custList = new List<CustomerCbx>()
{
new CustomerCbx{ Display = c1.Name, Value = c1},
new CustomerCbx{ Display = c2.Name, Value = c2},
}
InitDGVComboBoxColumn<CustomerCbx>(cbx, custList, "display", "value");
}
}
}
}
It seems pretty hacky to me, but I couldn't find any better way so far (that also works with complex objects other than just Strings). Hope that will save the search for some others ;)

You need to set the Items for the new cell. This must be auto done by the column when creating a new row from the UI.
var cell = new DataGridViewComboBoxCell() { Value = "SomeText" };
cell.Items.AddRange(new String[]{"SomeText", "Abcd", "123"});

something different worked for me what i did is to simply set the value of dtataGridComboBox when ever new record is added bu user with 'userAddedRow' event. For the first row I used the code in constructor.
public partial class pt_drug : PatientDatabase1_3._5.basic_templet
{
public pt_drug()
{
InitializeComponent();
dataGridView_drugsDM.Rows[0].Cells[0].Value = "Tablet";
}
private void dataGridView_drugsDM_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
dataGridView_drugsDM.Rows[dataGridView_drugsDM.RowCount - 1].Cells[0].Value = "Tablet";
}
}

Here the solution I have found : select the cell you are interested in so you can cast it to a combobox.
this.Invoke((MethodInvoker)delegate
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[yourRowindex].Cells[yourColumnIndex];
this.dataGridView1.BeginEdit(true);
ComboBox comboBox = (ComboBox)this.dataGridView1.EditingControl;
comboBox.SelectedIndex += 1;
});

Related

Adding Items to DataGridView from a ListBox to a Single Column

I need to populate a DataGridView with items from a List.
I need the first row of the GridView populated with the items from the String List and i need to do some processing on the items in the GridView one by one and add the result to the second row(String).
Currently im Binding the DataGridView like this
dataGridView1.DataSource = mylist.ConvertAll(x => new { Value = x });
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
I need to predefine the column name add strings in the first row,process these strings one by one and update the second column..what is the best way to do this?
here is your solution,
dgvDataViewer.ColumnCount = 1;
dgvDataViewer.Columns[0].Name = "Language";
string[] row = new string[] { "C#" };
dgvDataViewer.Rows.Add(row);
row = new string[] { "C++" };
dgvDataViewer.Rows.Add(row);
row = new string[] { "C" };
dgvDataViewer.Rows.Add(row);
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "HeaderText";
cmb.Name = "Name";
cmb.FlatStyle = FlatStyle.System;
dgvDataViewer.Columns.Add(cmb);
DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dgvDataViewer.Rows[0].Cells[1];
dgvcbc.Items.Add("Apple");
dgvcbc.Items.Add("Google");
dgvcbc.Items.Add("Apache");
dgvcbc.Items.Add("Microsoft");
Hope this will help you for your solution.
First you need to build your columns either programmatically or you can use the designer - that is up to you. I will code all of it for the sake of showing the entire example:
private DataGridView dgNew;
public MyForm()
{
InitializeComponent();
MyInitializeComponent();
}
private void MyInitializeComponent()
{
dgNew = new DataGridView();
var txtCol = new DataGridViewTextBoxColumn
{
HeaderText = "Column1",
Name = "Column1",
DataPropertyName = "Value"
};
dgNew.Columns.Add(txtCol);
txtCol = new DataGridViewTextBoxColumn
{
HeaderText = "Column2",
Name = "Column2",
};
dgNew.Columns.Add(txtCol);
var listOfStrings = new List<string> {"one", "two", "three"};
dgNew.DataSource = listOfStrings.ConvertAll(x => new { Value = x }); ;
dgNew.Location = dg.Location;
dgNew.Parent = this;
this.Load += Form_Load;
}
private void Form_Load(object sender, EventArgs e)
{
// Iterate over the rows, ignoring the header row
foreach (var row in dgNew.Rows.OfType<DataGridViewRow>().Where(a => a.Index != -1))
{
var col1Value = row.Cells["Column1"].Value?.ToString();
var col2Cell = row.Cells["Column2"];
if (col1Value == null) continue;
switch (col1Value)
{
case ("one"):
col2Cell.Value = "row1, col2 val";
break;
case ("two"):
col2Cell.Value = "row2, col2 val";
break;
case ("three"):
col2Cell.Value = "row1, col3 val";
break;
}
}
}

DataGridViewComboBoxCell : How to set selected value when adding a row?

I have this form that lets user choose a (Code - Product) item from a comboxbox. input quantity and price and Add it to a list.
Loading the inventories to the form
private List<Inventory> inventories = new Inventory().read_inventory();
Setting the ComboBox with values
private void set_drop_down_inventory()
{
cb_inventory.DisplayMember = "name";
cb_inventory.DataSource = inventories;
cb_inventory.ResetText();
cb_inventory.SelectedIndex = -1;
}
When a user selects a product, it will create a new instance.
private void cb_inventory_SelectionChangeCommitted(object sender, EventArgs e)
{
var selected_inventory = (cb_inventory.SelectedItem as Inventory);
sales_order_detail = new Sales_Order_Detail(selected_inventory, 0);
tx_description.Text = selected_inventory.description;
tx_price.Text = selected_inventory.get_price_str();
}
Once the user adds the item it triggers this code.
private void btn_add_item_Click(object sender, EventArgs e)
{
// Set the inputted data into the instance before adding to the list
sales_order_detail.description = tx_description.Text.ToString();
sales_order_detail.quantity = tx_quantity.Value;
sales_order_detail.price = Convert.ToDecimal(tx_price.Text);
// Adding the instances to a List
sales_order.sales_order_details.Add(sales_order_detail);
// Sets the Datagrid to provide the data+
initialize_datagrid(sales_order_detail);
}
This is how i initialize the datagrid because i need to manually display the columns -- this is where i am not sure what to do - i believe i do not need to manually add a new row every time a user adds an item because this datagrid is bounded to the List<>, so whatever instance is added to the List<> it will be added to the grid when i trigger the dgv.Refresh()
private void initialize_datagrid(Sales_Order_Detail sales_order_detail)
{
dgv_sales_order_details.Columns.Clear();
dgv_sales_order_details.DataSource = null;
dgv_sales_order_details.Refresh();
dgv_sales_order_details.AutoGenerateColumns = false;
// Set the datasource to the list where the item is added
dgv_sales_order_details.DataSource = sales_order.sales_order_details;
DataGridViewComboBoxColumn product_code_col = new DataGridViewComboBoxColumn();
DataGridViewColumn description_col = new DataGridViewColumn();
DataGridViewColumn quantity_col = new DataGridViewColumn();
DataGridViewColumn price_col = new DataGridViewColumn();
DataGridViewColumn account_col = new DataGridViewColumn();
DataGridViewComboBoxCell product_cell = new DataGridViewComboBoxCell();
DataGridViewTextBoxCell description_cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxCell amount_cell = new DataGridViewTextBoxCell();
product_cell.DisplayMember = "name";
// They have the same Datasource as the combobox above.
product_cell.DataSource = inventories;
product_code_col.CellTemplate = product_cell;
product_code_col.DataPropertyName = nameof(sales_order_detail.inventory.name); //This binds the value to your column
product_code_col.HeaderText = "Code";
product_code_col.Name = "name";
description_col.CellTemplate = description_cell;
description_col.DataPropertyName = nameof(sales_order_detail.description);
description_col.HeaderText = "Description";
description_col.Name = "description";
quantity_col.CellTemplate = amount_cell;
quantity_col.DataPropertyName = nameof(sales_order_detail.quantity);
quantity_col.HeaderText = "Quantity";
quantity_col.Name = "quantity";
quantity_col.DefaultCellStyle.Format = "0.00";
quantity_col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
price_col.CellTemplate = amount_cell;
price_col.DataPropertyName = nameof(sales_order_detail.price);
price_col.HeaderText = "Price";
price_col.Name = "price";
price_col.DefaultCellStyle.Format = "0.00";
price_col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dgv_sales_order_details.Columns.Add(product_code_col);
dgv_sales_order_details.Columns.Add(description_col);
dgv_sales_order_details.Columns.Add(quantity_col);
dgv_sales_order_details.Columns.Add(price_col);
dgv_sales_order_details.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
This is the result when the item is added but as you can see the combobox column has not displayed value, it only shows the value when i click the combobox column. and when i change the value in the combobox above the list, the value in the combobox column also changes. it seems that they are binded.
My Goal is to be able add a row to the datagrid where the comboboxcolumn displays what i selected and to fix to combobox duplicated selection.
Please comment if it needs more clarification so i could correct it. Thanks!
DataGridViewComboBoxColumn c = new DataGridViewComboBoxColumn();
c.Name = "ComboColumn";
c.DataSource = dataTable;
c.ValueMember = "ID";
c.DisplayMember = "Item";
dataGridView1.Columns.Add(c);
To select a particular value you set the Value property of a given cell.
dataGridView1.Rows[rowIndexYouWant].Cells["ComboColumn"].Value = 1;
Note that the type here is important! IF you say you get a System.FormatException. This can be caused by setting the wrong type to the value.
When you set the value to 1 you are assigning an int - if for some reason you have strings in the ID column you will get the System.FormatException exception you are seeing.
If the types differ you need to either update the DataTable definition or set the value to a string:
dataGridView1.Rows[rowIndexYouWant].Cells["ComboColumn"].Value = "1";
for adding rows you might need
dataGridView1.Rows.Add();
int z=0;
for (int a = 0; a < dataGridView1.comlumncount; a++)
{
dataGridView1.Rows[z].Cells[a].Value = "yourvalue";
z++;
}
for your reference check this Link you might get your problem solved
I've managed to solve it, this is my solution. This is best solution i've come up so far. Please comment if you have any correction. so we could improve it. I hope this will help others too.
Created a DataGridView Handler so i could reuse it in the other forms and add more conditions for it be flexible.
namespace Project.Classes
{
public static class DGV_Handler
{
public static DataGridViewComboBoxColumn CreateInventoryComboBox()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
// This lets the combo box display the data selected
// I set the datasource with new instance because if i use the Datasource used in the combobox in the item selection. the combobox in the grid and that combox will be binded. if i change one combobox the other one follows.
combo.DataSource = new Inventory().read_inventory();
combo.DataPropertyName = "inventory_id";
combo.DisplayMember = "name";
combo.ValueMember = "inventory_id";
combo.Name = "inventory_id";
combo.HeaderText = "Code";
combo.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
return combo;
}
public static DataGridViewComboBoxColumn CreateGLAccountComboBox()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = new Account().read();
combo.DataPropertyName = "gl_account_sales";
combo.DisplayMember = "account_name";
combo.ValueMember = "account_id";
combo.Name = "account_id";
combo.HeaderText = "Account";
combo.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
return combo;
}
public static DataGridViewTextBoxColumn CreateTextBox(string dataproperty, string headertext, string name, bool is_numbers)
{
DataGridViewTextBoxColumn textbox = new DataGridViewTextBoxColumn();
textbox.DataPropertyName = dataproperty;
textbox.HeaderText = headertext;
textbox.Name = name;
if (is_numbers)
{
textbox.DefaultCellStyle.Format = "0.00";
textbox.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
return textbox;
}
}
}
When the form is loaded i initialize the datagrid like this.
private void initialize_datagrid()
{
dgv_sales_order_details.Columns.Clear();
dgv_sales_order_details.Refresh();
dgv_sales_order_details.AutoGenerateColumns = false;
dgv_sales_order_details.DataSource = bindingSource1;
dgv_sales_order_details.Columns.Add(DGV_Handler.CreateInventoryComboBox());
dgv_sales_order_details.Columns.Add(DGV_Handler.CreateTextBox("description","Description", "description", false));
dgv_sales_order_details.Columns.Add(DGV_Handler.CreateTextBox("quantity","Quantity","quantity", true));
dgv_sales_order_details.Columns.Add(DGV_Handler.CreateTextBox("price", "Price", "price", true));
dgv_sales_order_details.Columns.Add(DGV_Handler.CreateGLAccountComboBox());
dgv_sales_order_details.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dgv_sales_order_details.RowHeadersVisible = false;
dgv_sales_order_details.EditMode = DataGridViewEditMode.EditOnEnter;
}
Code when adding a new row
private void btn_add_item_Click(object sender, EventArgs e)
{
if(validate_selection())
{
// Set the properties to be included in the DGV Column
var selected_row = (cb_inventory.SelectedValue as Inventory);
var selected_gl_account = (cb_gl_account.SelectedValue as Account);
string description = tx_description.Text;
decimal quantity = tx_quantity.Value;
decimal price = Convert.ToDecimal(tx_price.Text);
int gl_account_id = selected_gl_account.account_id;
// When something new is added to the bindingsource, the DGV will be refresh
bindingSource1.Add(new Sales_Order_Detail(selected_row, description, quantity, price, 0, gl_account_id));
clear_item_selection();
}
}
Result

Set value to ComboBoxCell in DataGridView

I want to set a value for a cell that is actually a comboboxcell. I done it for my another project but now the same way, doesnt work!!
here is my code
//dgExcel is my datagridview
var cmb = (DataGridViewComboBoxColumn)dgExcel.Columns[1];
cmb.DataSource = sucTurleri; //its a list
cmb.DisplayMember = "SucTuru";
cmb.ValueMember = "Id";
and this code is adding row to the grid
var Konumlar = ExcelYardimcisi.KonumlariExceldenAl(dg.FileName);
foreach (var konum in Konumlar)
{
dgExcel.Rows.Add(konum.KonumAdi, sucTurleri[0].SucTuru, DateTime.Now.ToShortDateString());
}
but i got an error and i used this
foreach (var konum in Konumlar)
{
dgExcel.Rows.Add(konum.KonumAdi, null, DateTime.Now.ToShortDateString());
DataGridViewComboBoxCell cbox = (DataGridViewComboBoxCell)dgExcel.Rows[dgExcel.Rows.Count - 1].Cells[1];
cbox.Value = sucTurleri[0].SucTuru;
}
and the error is
Your data binding part is pretty OK. The problem is with dgExcel.Rows.Add() method.
Here is a sample code:
List<Item> items = new List<Item>();
items.Add(new Item() { Name = "One", Id = 1 });
items.Add(new Item() { Name = "Two", Id = 2 });
var cbo = dataGridView1.Columns[1] as DataGridViewComboBoxColumn;
cbo.DataSource = items;
cbo.ValueMember = "Id";
cbo.DisplayMember = "Name";
dataGridView1.Rows.Add("test", items[1].Id);
...
public class Item
{
public string Name { get; set; }
public int Id { get; set; }
}
Because the DataGridViewComboBoxColumn is data bound, you have to set the value by ValueMember, in my case items[1].Id. You have to to this in your code as well.

How do you Programmatically set DataGridViewComboBoxCell value?

I'm having trouble setting the value of DataGridViewComboBoxCell. The datagridview column is bound with choices/values but when I attempt either dgv.Rows.Add with specified column values for the comboBoxCells OR setting the cell's value seperately, it generates the "DataGridViewComboBoxCell value is not valid" error. If I add a row with blank values for those column, the choices display in the combo just fine.
I have a dialog that is passed an arraylist of a simple object, NDCRecord.
public class NDCRecord
{
public string NDCcode = "";
public string UnitQuantity = "";
public string UnitOfMeasurement = "";
public string Type = "";
public string Number = "";
}
In the dialog a datagrid is created programmatically and then is repopulated.
public NationalDrugCodesForm(ref ArrayList ndcRecordsIn)
{
InitializeComponent();
ndcRecords = ndcRecordsIn;
SetupDataGridViewColumns();
PopulateForm();
}
Setup:
private void SetupDataGridViewColumns()
{
// -----------------------------------------------------
// Add/Del column
// -----------------------------------------------------
DataGridViewButtonColumn dgvbcAddRemove = new DataGridViewButtonColumn();
dgvbcAddRemove.HeaderText = "Add";
dgvbcAddRemove.Text = "Add";
dgvbcAddRemove.Name = "Add";
DataGridViewCellStyle addButtonStyle = new DataGridViewCellStyle();
addButtonStyle.BackColor = Color.Blue;
addButtonStyle.ForeColor = Color.White;
dgvbcAddRemove.HeaderCell.Style = addButtonStyle;
dgvNDC.Columns.Add(dgvbcAddRemove);
// -----------------------------------------------------
// Additional Columns
// -----------------------------------------------------
dgvNDC.Columns.Add("NDCCode", "NDC Code");
dgvNDC.Columns.Add("UnitQuantity", "Unit Quantity");
DataGridViewComboBoxColumn unitOfMeasurement = new DataGridViewComboBoxColumn();
unitOfMeasurement.HeaderText = "Unit Of Measurement";
unitOfMeasurement.Name = "UnitOfMeasurement";
dgvNDC.Columns.Add(unitOfMeasurement);
DataGridViewComboBoxColumn type = new DataGridViewComboBoxColumn();
type.HeaderText = "Type";
type.Name = "Type";
dgvNDC.Columns.Add(type);
dgvNDC.Columns.Add("Number", "Prescription Number");
AddLine("Del", "", "", "", "", "");
BindUnitOfMeasurement((DataGridViewComboBoxCell)dgvNDC.Rows[0].Cells["UnitOfMeasurement"]);
BindType((DataGridViewComboBoxCell)dgvNDC.Rows[0].Cells["Type"]);
}
The AddLine function:
private void AddLine(string buttonLabel, string ndcCode, string unitQuantity, string unitOfMeasurement, string type, string rxNumber)
{
dgvNDC.Rows.Add(new object[] { buttonLabel, ndcCode, unitQuantity, unitOfMeasurement, type, rxNumber });
}
The binding functions:
private void BindUnitOfMeasurement(DataGridViewComboBoxCell cb)
{
string[] Values = { "F2", "GR", "ME", "ML", "UN" };
string[] Choices = { "F2 - International Unit", "GR - Gram", "ME - Milligram", "ML - Milliliter", "UN - Unit" };
ControlManip.DataBindDDL(cb, Choices, Values);
}
private void BindType(DataGridViewComboBoxCell cb)
{
string[] Values = { "XZ", "VY" };
string[] Choices = { "XZ - Prescription Number", "VY - Link Sequence Number" };
ControlManip.DataBindDDL(cb, Choices, Values);
cb.Value = "XZ";
}
public static void DataBindDDL(ref ComboBox cb, string[] Choices, string[] Values)
{
DataTable dt = new DataTable();
dt.Columns.Add("Choice");
dt.Columns.Add("Value");
if (Choices.Length != Values.Length)
{
throw new Exception("Number of Choices and Values do not match!");
}
else
{
dt.Rows.Add(new object[] { "", "" });
for (int i = 0; i < Choices.Length; i++)
{
if (Choices[i] is object && Values[i] is object)
{
dt.Rows.Add(new object[] { Choices[i], Values[i] });
}
}
cb.DataSource = dt;
cb.DisplayMember = "Choice";
cb.ValueMember = "Value";
}
}
Populate the form:
private void PopulateForm()
{
if (ndcRecords == null || ndcRecords.Count == 0)
return;
dgvNDC.Rows.Clear();
foreach(NDCRecord record in ndcRecords)
{
AddLine("Del", record.NDCcode, record.UnitQuantity, record.UnitOfMeasurement, record.Type, record.Number);
}
}
The problem was that I was binding individual CELLs instead of the COLUMNS that contained the drop-down box. I had inserted bind methods where the "Add" button was clicked that made it appear as though adding a row with blank values still resulted in populated dropdowns. But adding a row with values specified caused an error because the row's dropdown columns had nothing in their collection yet. So here are the important modifications to the code:
In SetupDataGridViewColumns instead of
BindUnitOfMeasurement((DataGridViewComboBoxCell)dgvNDC.Rows[0].Cells["UnitOfMeasurement"]);
BindType((DataGridViewComboBoxCell)dgvNDC.Rows[0].Cells["Type"]);
use
BindUnitOfMeasurement((DataGridViewComboBoxColumn)dgvNDC.Columns["UnitOfMeasurement"]);
BindType((DataGridViewComboBoxColumn)dgvNDC.Columns["Type"]);
and modify the binding methods appropriately. Then, you can add a row with blank values for the combo, or specified values, and it will work (below one of them has a value specified for default, the other is left blank for the user to select from)
AddLine("Del", "", "", "", "XZ", "");
Also, I'm not sure if this was necessary but in the course of experimenting I also added this for each combobox column:
type.ValueType = typeof (string);

How to bind list to dataGridView?

I seem to be running around in circles and have been doing so in the last hours.
I want to populate a datagridview from an array of strings. I've read its not possible directly, and that I need to create a custom type that holds the string as a public property. So I made a class:
public class FileName
{
private string _value;
public FileName(string pValue)
{
_value = pValue;
}
public string Value
{
get
{
return _value;
}
set { _value = value; }
}
}
this is the container class, and it simply has a property with the value of the string. All I want now is that string to appear in the datagridview, when I bind its datasource to a List.
Also I have this method, BindGrid() which I want to fill the datagridview with. Here it is:
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn();
DataGridViewCell cell = new DataGridViewTextBoxCell();
colFileName.CellTemplate = cell; colFileName.Name = "Value";
colFileName.HeaderText = "File Name";
colFileName.ValueType = typeof(FileName);
//add the column to the datagridview
gvFilesOnServer.Columns.Add(colFileName);
//fill the string array
string[] filelist = GetFileListOnWebServer();
//try making a List<FileName> from that array
List<FileName> filenamesList = new List<FileName>(filelist.Length);
for (int i = 0; i < filelist.Length; i++)
{
filenamesList.Add(new FileName(filelist[i].ToString()));
}
//try making a bindingsource
BindingSource bs = new BindingSource();
bs.DataSource = typeof(FileName);
foreach (FileName fn in filenamesList)
{
bs.Add(fn);
}
gvFilesOnServer.DataSource = bs;
}
Finally, the problem: the string array fills ok, the list is created ok, but I get an empty column in the datagridview. I also tried datasource= list<> directly, instead of = bindingsource, still nothing.
I would really appreciate an advice, this has been driving me crazy.
Use a BindingList and set the DataPropertyName-Property of the column.
Try the following:
...
private void BindGrid()
{
gvFilesOnServer.AutoGenerateColumns = false;
//create the column programatically
DataGridViewCell cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
{
CellTemplate = cell,
Name = "Value",
HeaderText = "File Name",
DataPropertyName = "Value" // Tell the column which property of FileName it should use
};
gvFilesOnServer.Columns.Add(colFileName);
var filelist = GetFileListOnWebServer().ToList();
var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList
//Bind BindingList directly to the DataGrid, no need of BindingSource
gvFilesOnServer.DataSource = filenamesList
}
may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you
public class FileName
{
[DisplayName("File Name")]
public string FileName {get;set;}
[DisplayName("Value")]
public string Value {get;set;}
}
and then you can bind List as datasource as
private void BindGrid()
{
var filelist = GetFileListOnWebServer().ToList();
gvFilesOnServer.DataSource = filelist.ToArray();
}
for further information you can visit this page Bind List of Class objects as Datasource to DataGridView
hope this will help you.
I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.
public class FileName
{
public string ThisFieldWorks {get;set;}
public string ThisFieldDoesNot;
}
Instead of create the new Container class you can use a dataTable.
DataTable dt = new DataTable();
dt.Columns.Add("My first column Name");
dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item number 2" });
dt.Rows.Add(new object[] { "Item number three" });
myDataGridView.DataSource = dt;
More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString
Using DataTable is valid as user927524 stated.
You can also do it by adding rows manually, which will not require to add a specific wrapping class:
List<string> filenamesList = ...;
foreach(string filename in filenamesList)
gvFilesOnServer.Rows.Add(new object[]{filename});
In any case, thanks user927524 for clearing this weird behavior!!

Categories