设置datagridviewcomboboxcell值

时间:2012-11-05 07:12:36

标签: vb.net winforms

我有以下代码来绑定适当的组合框单元格:

Const colIndex As Integer = 1
        Dim dgvcombo As DataGridViewComboBoxCell
        dgvcombo = gvMain.Rows(_rowindex).Cells("SerialNumber")
        dtGrpBrand = getDataTable("select * from (select SSPERPSerialMaster.ProductID,SSPERPSerialMaster.SizeID,SSPERPSerialMaster.GaugeID, SSPERPSerialMaster.SerialID,SSPERPSerialMaster.SerialNumber,ISNULL(SSPERPSerialEntryOpening.Qty,0)+ISNULL(a.Stock,0) as [Closing Qty] " & _
                        "from SSPERPProductMaster " & _
                        "left join SSPERPSerialMaster on SSPERPSerialMaster.ProductID=SSPERPProductMaster.ProductID " & _
                        "left join SSPERPSerialEntryOpening on SSPERPSerialEntryOpening.SerialID=SSPERPSerialMaster.SerialID and SSPERPSerialMaster.ProductID=SSPERPSerialEntryOpening.ProductID " & _
                        "left join (select SerialId,SUM(ISNULL(case when AL='A' then Qty else - Qty end, 0)) as [Stock] from SSPERPStock group by SerialId) a on a.SerialId=SSPERPSerialMaster.SerialID) a " & _
                        "where a.[Closing Qty]<>0 and a.ProductID=" & gvMain.Rows(_rowindex).Cells("ProductId").Value.ToString() & " and a.SizeID=" & gvMain.Rows(_rowindex).Cells("SizeId").Value.ToString() & " and a.GaugeID=" & gvMain.Rows(_rowindex).Cells("GaugeId").Value.ToString(), CompanyCon)
        dtGrpBrand.Rows.Add()
        dtGrpBrand.Rows(dtGrpBrand.Rows.Count - 1)("SerialNumber") = "-- Select --"
        dtGrpBrand.Rows(dtGrpBrand.Rows.Count - 1)("SerialId") = 0
        dgvcombo.AutoComplete = True
        CType(gvMain.Rows(_rowindex).Cells(colIndex), DataGridViewComboBoxCell).DataSource = dtGrpBrand
        CType(gvMain.Rows(_rowindex).Cells(colIndex), DataGridViewComboBoxCell).DisplayMember = "SerialNumber"
        CType(gvMain.Rows(_rowindex).Cells(colIndex), DataGridViewComboBoxCell).ValueMember = "SerialId"
        CType(gvMain.Rows(_rowindex).Cells(colIndex), DataGridViewComboBoxCell).Value = 0

这个代码在我的应用程序中完美地工作,而我有插入数据模式,但是当用户从列表中选择记录时,我需要动态地绑定“SerialNumber”的单元格, 在那个时候我也正确地通过这个代码绑定datagridviewcimboboxcell,它正确地绑定我的组合框,但当我给出以下代码设置值时它不起作用并给我错误:

gvMain.Rows(gvMain.Rows.Count - 1).Cells("SerialNumber").Value = dtrow("SerialId")

我也尝试过以下行来获取所选值但没有解决方案:

CType(gvMain.Rows(gvMain.Rows.Count - 1).Cells("SerialNumber"), DataGridViewComboBoxCell).Value = dtrow("SerialId")

这里gvmain是datagridview,dtrow是datarow

2 个答案:

答案 0 :(得分:0)

dtrow("SerialId")返回一个Object。您显然对该值感兴趣,请尝试dtrow("SerialId").ToString

gvMain.Rows(gvMain.Rows.Count - 1).Cells("SerialNumber").Value = dtrow("SerialId").ToString

答案 1 :(得分:0)

DataGridViewComboboxCell具有DataSource属性。尝试使用以下方法设置值:

   Dim lst As New List(Of String)()
   lst.Add(dtrow("SerialId").ToString)
   DirectCast(DataGridView1.Rows(gvMain.Rows.Count - 1).Cells("SerialNumber"), DataGridViewComboBoxCell).DataSource = lst

它应该解决问题。