[英]How to set and get the value of Data Bind Gridview Combobox Column in C#
I have a data grid view with combo box column in it, i have bind that column to datatable like this: 我有一个带有组合框列的数据网格视图,我已经将该列绑定到数据表,如下所示:
((grdItems.Columns[1]) as DataGridViewComboBoxColumn).DataSource = dt;
((grdItems.Columns[1]) as DataGridViewComboBoxColumn).DisplayMember = "LocationName";
((grdItems.Columns[1]) as DataGridViewComboBoxColumn).ValueMember = "Id";
now i can get the selected value like this: 现在我可以像这样获得选定的值:
var value = grdItems.Rows[0][1].Value;
but the issue is, when i manually add the rows in the gridview (without binding the grid), i cant get the value of the combobox cell. 但是问题是,当我在gridview中手动添加行(不绑定网格)时,我无法获取组合框单元格的值。 i am adding rows like this: 我正在添加这样的行:
grdItems.Rows.Add(1, 1, "Some Value");
when i use var value = grdItems.Rows[0][1].Value; 当我使用var value = grdItems.Rows [0] [1] .Value; this method to get the value, i returns me the text of the cell not the value ie 1 in this case. 这种方法来获取值,在这种情况下,我向我返回单元格的文本而不是值(即1) 。
How can i solve this issue? 我该如何解决这个问题? since i want the value of the cell in case of adding rows manually, as well as data-bind rows. 因为我想要在手动添加行以及数据绑定行的情况下该单元格的值。
Am assuming that by manually adding rows you mean from the UI , so one way to get the value of the newly added row is to use an event handler
for the events
raised when you add an row. 我假设通过手动添加行是您从UI的意思,因此获取新添加的行的值的一种方法是对添加行时引发的events
使用event handler
。 You may use one of the following 1) RowsAdded
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowsadded(v=vs.110).aspx 2) RowPrePaint
- https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowprepaint(v=vs.110).aspx - not used this much but is also an option 您可以使用以下1)的一个RowsAdded
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowsadded(v=vs.110).aspx 2) RowPrePaint
- HTTPS: //msdn.microsoft.com/zh-CN/library/system.windows.forms.datagridview.rowprepaint(v=vs.110).aspx-使用的次数不多,但也可以选择
this.myGridView.RowsAdded += new DataGridViewRowsAddedEventHandler(myGridView_RowsAdded);
private void myGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
var newRow = this.myGridView.Rows[e.RowIndex];
}
Edit: Based on the actual requirement stated in the comments - actual requirement being retrieving the newly added row's cell value (Id) corresponding to the combox box column on button save clicked event 编辑:基于注释中所述的实际需求-实际需求是检索与按钮保存单击事件上的combox框列对应的新添加的行的单元格值(Id)
Assuming you have bound the combo box to a data source itself , meaning, your 假设您已将组合框绑定到数据源本身,也就是说,您的
combobox.DataSource=someList
so what you can do is write a linq query 所以你可以做的是写一个linq查询
someList.Where( v=>v.Text.Equals("row.Cells[1].Value")).FirstOrDefault().Id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.