vb.net 向现有动态数据表添加新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3793844/
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
Add a new row to an existing dynamic datatable
提问by Troels
I have a dynamic datatable, created from a database. I want to add a new row (blank), so there is an option to choose nothing in a combobx. Everything works ok without adding the new row. But when I add a new row, the combobox displays nothing. What am I missing?
我有一个从数据库创建的动态数据表。我想添加一个新行(空白),因此可以选择在 combobx 中不选择任何内容。一切正常,无需添加新行。但是当我添加新行时,组合框什么也不显示。我错过了什么?
Here is the code
这是代码
Dim DT As New DataTable
DT = DS.Tables("CallStatus")
Dim drNewRow As DataRow = DT.NewRow
'Add new row
drNewRow.Item("CampaignCallStatusID") = ""
drNewRow.Item("CampaignCallStatus") = ""
DT.Rows.Add(drNewRow)
DT.AcceptChanges()
'Fill combobox
With cboCallStatus
.DataSource = DT
.DisplayMember = "CampaignCallStatus"
.ValueMember = "CampaignCallStatusID"
End With
回答by Troels
I found a solution. I used the method InsertAt, and plased the row in the top.
我找到了解决方案。我使用了 InsertAt 方法,并将行放在顶部。
Dim DT As New DataTable
DT = DS.Tables("CallStatus")
Dim drNewRow As DataRow = DT.NewRow
DT.Rows.InsertAt(drNewRow, 0) ' <== This is the solution
DT.AcceptChanges()
With cboCallStatus
.DataSource = DT
.DisplayMember = "CampaignCallStatus"
.ValueMember = "CampaignCallStatusID"
End With
cboCallStatus.Refresh()
回答by Tim Murphy
In your example the CampaignCallStatus for the blank row is empty therefore the display in the combobox will be empty. If you believe that one of the database values should be displayed at the record that you are currently displaying then change the blank row CampaignCallStatus to a value (say Debug) to confirm the blank row is being displayed.
在您的示例中,空白行的 CampaignCallStatus 为空,因此组合框中的显示将为空。如果您认为应在当前显示的记录中显示其中一个数据库值,则将空行 CampaignCallStatus 更改为一个值(例如 Debug)以确认正在显示该空行。
More than likely the reason the blank row is shown in the combobox is because of the CampaignCallStatusID is not the same type as database type for CampaignCallStatusID. Try changing the blank row value from "" to 0.
组合框中显示空白行的原因很可能是因为 CampaignCallStatusID 的类型与 CampaignCallStatusID 的数据库类型不同。尝试将空白行值从 "" 更改为 0。
回答by Alex Essilfie
You can try iterating through all the desired rows and adding them manually to the ComboBox.
An example is as follows:
您可以尝试遍历所有所需的行并将它们手动添加到 ComboBox。
一个例子如下:
ComboBox.Items.Clear()
For Each dr as DataRow in DT.Rows
ComboBox.Items.Add(dr("col1").ToString())
Next
This is guaranteed to work when data binding fails.
这保证在数据绑定失败时有效。