1

如果我有一个名为“汽车”的类,并且这个汽车类使用 SQL 查询来填充 ID、名称、类型、型号、引擎和大小等属性。如何使用该数据填充 asp:formview?

我试过这个:

Private currentCar As car        
fvCarview.DataSource = currentCar 
fvCarview.DataBind()

但我不断收到此错误:

Data source is an invalid type.  It must be either an IListSource, IEnumerable, or IDataSource.

任何帮助,将不胜感激!

谢谢

4

1 回答 1

2

一种简单的方法是使用 a List(Of Car),其中只有一辆汽车或一个IEnumerable(Car)via carList.Where(Function(c) c.ID = carID)。您也可以使用 aSqlDataAdapter来填充 aDataTabletable.Where(Function(r) r.Field(Of Int32)("ID") = carID)。或者只是从数据库中选择单辆车,这也是当您不需要完整列表时最有效的方式:

数据表:

Private Sub fillFormView(carID As Int32)
    Using con = New SqlConnection(My.Settings.SqlConnection)
        Using da = New SqlDataAdapter("SELECT ID, Name, Type, Model, Engine, Size FROM TCAR WHERE ID=@ID", con)
            da.SelectCommand.Parameters.AddWithValue("@ID", carID)
            Dim table = New DataTable
            da.Fill(table)
            fvCarview.DataSource = table
            fvCarview.DataBind()
        End Using
    End Using
End Sub

这是您的自定义 Car-Class 方法,其中包含一辆汽车List(Of Car)

Class Car
    Public Property ID As Int32
    Public Property Name As String
    Public Property Type As String
    Public Property Model As String
    Public Property Engine As String
    Public Property Size As Double
End Class

Private Sub fillFormView(carID As Int32)
    Using con = New SqlConnection(My.Settings.SqlConnection)
        Using cmd = New SqlCommand("SELECT ID, Name, Type, Model, Engine, Size FROM TCAR WHERE ID=@ID", con)
            cmd.Parameters.AddWithValue("@ID", carID)
            con.Open()
            Using rd = cmd.ExecuteReader()
                rd.Read()
                Dim carList = New List(Of Car)
                Dim car = New Car()
                car.ID = rd.GetInt32(0)
                car.Name = rd.GetString(1)
                car.Type = rd.GetString(2)
                car.Model = rd.GetString(3)
                car.Engine = rd.GetString(4)
                car.Size = rd.GetDouble(5)
                carList.Add(car)
                fvCarview.DataSource = carList
                fvCarview.DataBind()
            End Using
        End Using
    End Using
End Sub
于 2012-11-05T20:44:02.157 回答