![](/img/trans.png)
[英]How do you convert a cell value in a DataGridView into a integer if it's an integer, and a string when it's a string?
[英]How to display a string value in a integer cell of DataGridView?
這段代碼從數據庫填充DataGridView
。 Volunteers.Status
.Status在數據庫級別定義為Integer。
我想在Status列中顯示一個字符串而不是整數,但是當我嘗試將DataGridView1.Rows(row.Index).Cells(14).Value
設置為字符串時,應用程序失敗。
Error: INACTIVE is not a valid value for Int32
碼
SQL = "SELECT Volunteers.VolunteerID, Volunteers.NameVol AS Nombre, Volunteers.Surname AS Apellidos, Volunteers.email, Volunteers.Address AS Dirección, " & _
"Volunteers.ID AS DNI, Volunteers.DateOfBirth AS Fecha, Volunteers.PostalCode AS CP, Volunteers.City AS Ciudad, Volunteers.Province AS Provincia, Volunteers.Phone AS Telefono, " & _
"Volunteers.Studies AS Estudios, Volunteers.Vehicle AS Vehículo, Volunteers.Clothes AS Camiseta, Volunteers.Status AS Estado FROM Volunteers " & _
"LEFT JOIN ActivityVolunteer ON Volunteers.VolunteerID = ActivityVolunteer.VolunteerID " & _
"WHERE ActivityVolunteer.ActivityID = " & IDAct
Dim ds1 As New DataSet
Dim DA As New System.Data.OleDb.OleDbDataAdapter(SQL, SQLConnection)
DA.Fill(ds1)
DataGridView1.DataSource = ds1.Tables(0)
For Each row As DataGridViewRow In DataGridView1.Rows
Select Case DataGridView1.Rows(row.Index).Cells(14).Value
Case 0
DataGridView1.Rows(row.Index).Cells(14).Value = "INACTIVE"
Case 1
DataGridView1.Rows(row.Index).Cells(14).Value = "ACTIVE"
Case 2
DataGridView1.Rows(row.Index).Cells(14).Value = "OTHER"
End Select
Next
更新:
然后我嘗試了一個技巧,使該列不可見,然后添加一個額外的列,其中包含基於隱藏列的值。
DataGridView1.Columns(14).Visible = False
DataGridView1.Columns.Add("Estado", "Estado")
For Each row As DataGridViewRow In DataGridView1.Rows
DataGridView1.Rows(row.Index).Cells(15).Value = Convert(row.Cells(14).Value)
Next
Function Convert(ByVal e As Integer) As String
Select Case e
Case 0
Return "INACTIVE"
Case 1
Return "ACTIVE"
Case 2
Return "OTHER"
End Select
Return String.Empty
End Function
此更改不會引發任何異常,但新列上的單元格為空。
我怎樣才能做到這一點?
這段代碼根本不應該編譯:
Function Convert(ByRef e As Integer) As Integer
Select Case e
Case 0
e = "INACTIVE"
Case 1
e = "ACTIVE"
Case 2
e = "OTHER"
End Select
Return e
End Function
你傳遞一個整數byref ...(為什么?)...並試圖給它分配一個字符串值,然后返回它。 你要:
Function Convert(ByVal e As Integer) As String
Select Case e
Case 0
return "INACTIVE"
Case 1
return "ACTIVE"
Case 2
return "OTHER"
End Select
return String.Empty
End Function
試試這個,看看你得到了什么。 我懷疑.CellFormatting事件可能不是你應該在這里處理的事情,但是給它一個機會。
我會更改sql語句以獲取您需要的字符串,如下所示
SELECT Volunteers.VolunteerID, StatusString =
CASE Volunteers.Status
WHEN 0 THEN 'INACTIVE'
WHEN 1 THEN 'ACTIVE'
ELSE 'OTHER'
END, ............
FROM ......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.