vb.net 如何为 DataGridView 设置默认的 ComboBox 选定值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20796611/
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-09-17 16:15:41  来源:igfitidea点击:

How to set Default ComboBox Selected Value for a DataGridView?

.netvb.netdatagridview

提问by SamuraiHyman

I have a DataGridView in which I have a ComboBox column. The problem is by default there is always a blank value selected in a combobox but I want to ensure that default value is always some value which is a member or combobox.

我有一个 DataGridView,其中有一个 ComboBox 列。问题是默认情况下,组合框中总是选择一个空白值,但我想确保默认值始终是某个成员或组合框的值。

If DataGridView1.Rows.Count > 0 Then


            For Each row As DataGridViewRow In DataGridView1.Rows
                'row.Cells("ColDrCr").Value = "Debit"
                If row.Cells("ColDrCr").Value.ToString().Trim = "Credit" Then
                    result += Convert.ToDouble(row.Cells("ColAmount").Value)
                End If
                If row.Cells("ColDrCr").Value.ToString().Trim = "Debit" Then
                    result1 += Convert.ToDouble(row.Cells("ColAmount").Value)
                End If
            Next
            txtTotal.Text = result1 - result
        End If

As you can see I am checking weather the selected combobox value is Debit or Credit. But when a new row is added to the DataGridView it is always blank which I want to prevent. I want to set the default value to Debit or Credit. I tried ColDrCr.DefaultCellStyle. = "Credit"but it did not work because it only displays the text as Credit but when you check the value of row.Cells("ColDrCr").Value.ToString().Trim = "Debit"it returns null

如您所见,我正在检查天气,选择的组合框值是借方还是贷方。但是当一个新行被添加到 DataGridView 时,它总是空白,我想阻止它。我想将默认值设置为借方或贷方。我试过了,ColDrCr.DefaultCellStyle. = "Credit"但它没有用,因为它只将文本显示为 Credit 但当你检查row.Cells("ColDrCr").Value.ToString().Trim = "Debit"它的值时返回 null

I will accept answers in C# as well if they can be converted to vb using online tools.

如果可以使用在线工具将它们转换为 vb,我也将接受 C# 中的答案。

回答by tezzo

If you have a DataSetor a DataTableas a DataSourceof your DataGridViewyou can set the default value for a column.

如果您有 aDataSet或 aDataTable作为DataSource您的a ,DataGridView则可以为列设置默认值。

For example:

例如:

YourDataTable.Columns("ColDrCr").DefaultValue = "Debit"

回答by desw

The Simplest way is updating the DataTable properties just before its bound to. However you may not be able to call DataTable properties as methods as this may throw errors. The solution is to perceive them as arrays.

最简单的方法是在绑定之前更新 DataTable 属性。但是,您可能无法将 DataTable 属性作为方法调用,因为这可能会引发错误。解决方案是将它们视为数组。

Instead of this

而不是这个

dataTable.Columns("ColDrCr").DefaultValue = "Credit"

Use this

用这个

dataTable.Columns["ColDrCr"].DefaultValue = "Credit"