上周我发布了一个问题但是我没有理由为第一个答案设置显示成员或值成员。
查看其他论坛,我得知的是,如果我使用List绑定到DataGridViewComboBoxColumn
,那么我应该很容易得到所选值。
我发布的问题是:
Setting DataGridViewComboBoxColumn.Valuemember to a list<string>
我现在有了这段代码:
// set values to combobox column cells in datagridview
GridSellProducts.Rows.Add();
DataGridViewComboBoxColumn cmbItems = (DataGridViewComboBoxColumn)GridSellProducts.Columns["Item"];
cmbItems.DataSource = productNames;
cmbItems.AutoComplete = true;
GridSellProducts.EditingControlShowing += new
DataGridViewEditingControlShowingEventHandler(GridSellProducts_EditingControlShowing);
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
string itemValue = GridSellProducts.Rows[GridSellProducts.CurrentCell.RowIndex].Cells["Item"].FormattedValue.ToString();
.......code
}
但是上面的字符串itemValue的值总是为null,即string itemValue =“”;当我运行我的代码。这是为什么?
添加了:
这就是我填充productNames的方式
private void AutocompleteItems()
{
// get products
productsURL = "https://eko-app.com/Products/list_products/sessionId:" + sessionID + ".json";
var products = Products.GetProducts(productsURL);
List<string> productNames = new List<string>();
foreach (var p in products)
{
var x = p.Product;
foreach (var pn in x)
{
productNames.Add(pn.name);
}
}
// set values to combobox column cells in datagridview
GridSellProducts.Rows.Add();
DataGridViewComboBoxColumn cmbItems = (DataGridViewComboBoxColumn)GridSellProducts.Columns["Item"];
cmbItems.DataSource = productNames;
cmbItems.AutoComplete = true;
GridSellProducts.EditingControlShowing += new
DataGridViewEditingControlShowingEventHandler(GridSellProducts_EditingControlShowing);
}
类产品
//some code
public class Product
{
public string product_id { get; set; }
public string name { get; set; }
public decimal selling { get; set; }
public decimal buying { get; set; }
public string default_tax_tier { get; set; }
public string quantity_available { get; set; }
}
答案 0 :(得分:0)
我遇到了同样的问题。答案有点晚,但我希望它有所帮助。我没有设置列的数据源,而是将对象分别添加到列中,如下所示:
DataGridViewComboBoxColumn column = (DataGridViewComboBoxColumn)GridSellProducts.Columns["Item"];
foreach (string productname in productNames)
{
column.Items.Add(productname);
}
this.ValueType = typeof(string);
// if you use a custom object instead of a string, set these values:
// this.DisplayMember = "value";
// this.ValueMember = "hiddenValue";
然后,您可以通过从事件处理程序中的DataGridViewComboBoxEditingControl获取selecteditem来获取对象的值(字符串或其他内容)。此项将是添加到列项的对象(在本例中为字符串)。对我有用的代码是:
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
var sendingCB = sender as DataGridViewComboBoxEditingControl;
var currentcell = mappingDataGridView.CurrentCellAddress;
if (currentcell.X == 0)
{
object value = sendingCB.SelectedItem;
if (value != null)
{
string itemValue = (string)sendingCB.SelectedItem;
//
// or with an other object it looks like this:
// int intValue = ((ComboBoxItem)sendingCB.SelectedItem).hiddenValue;
}
}
}
我使用了this帖子来了解如何使用DataGridViewComboBoxColumn的事件处理程序。希望这会帮助某人:)。