C# 在 DataGridViewComboboxColumn 上设置所选项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/92035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:34:27  来源:igfitidea点击:

Set selected item on a DataGridViewComboboxColumn

提问by leora

I have a datagridview with a DataGridViewComboboxColumn column with 3 values:

我有一个带有 DataGridViewComboboxColumn 列的 datagridview,其中包含 3 个值:

"Small", "Medium", "Large"

“小号中号大号”

I get back the users default which in this case is "Medium"

我取回用户默认值,在这种情况下是“中”

I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.

我想在 datagridview 中显示一个下拉单元格,但默认值为“中”。我会在常规组合框中执行此操作,方法是执行选定的索引或仅设置组合框的 Text 属性。

采纳答案by leora

When you get into the datagridview it is probably best to get into databinding. This will take care of all of the selected index stuff you are talking about.

当您进入 datagridview 时,最好进入数据绑定。这将处理您正在谈论的所有选定索引内容。

However, if you want to get in there by yourself,

但是,如果你想自己进去,

DataGridView.Rows[rowindex].Cells[columnindex].Value 

will let you get and set the value associated to the DataGridViewComboBoxColumn. Just make sure you supply the correct rowindex and columnindex along with setting the value to the correct type (the same type as the ValueMember property of the DataGridViewComboBoxColumn).

将让您获取和设置与 DataGridViewComboBoxColumn 关联的值。只需确保提供正确的 rowindex 和 columnindex,并将值设置为正确的类型(与 DataGridViewComboBoxColumn 的 ValueMember 属性相同的类型)。

回答by leora

Are you retrieving the user data and attempting to set values in the DataGridView manually, or have you actually bound the DataGridVew to a data source? Because if you've bound the grid to a data source, you should just need to set the DataPropertyName on the column to be the string name of the object Property:

您是在检索用户数据并尝试手动在 DataGridView 中设置值,还是实际上将 DataGridVew 绑定到数据源?因为如果您已将网格绑定到数据源,则只需要将列上的 DataPropertyName 设置为对象属性的字符串名称:

[DataGridViewComboboxColumnName].DataPropertyName = "PropertyNameToBindTo";

Or do you mean you want it to default to Medium for a new row?

或者你的意思是你想让它默认为新行的中等?

回答by Sandeep Pathak

Do accomplish this task you should do something like this:-

要完成此任务,您应该执行以下操作:-

          this.dataGridViewStudentInformation.Columns[ColumnIndex].DataPropertyName = dataGridViewStudentInformation.Columns[2].Name ; //Set the ColumnName to which you want to bind.  

And set the default value in Database as Medium.

并将数据库中的默认值设置为中。

回答by user2866884

DataGridViewComboBoxColumn ColumnPage = new DataGridViewComboBoxColumn();
ColumnPage.DefaultCellStyle.NullValue = "Medium";