填写形式视图

时间:2012-11-05 20:26:29

标签: asp.net vb.net

如果我有一个名为“car”的类,这个汽车类使用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.

任何帮助将不胜感激!

由于

1 个答案:

答案 0 :(得分:2)

一种简单的方法是使用List(Of Car)一辆车或一辆IEnumerable(Car)通过carList.Where(Function(c) c.ID = carID)。您还可以使用SqlDataAdapter填充DataTabletable.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

这是您在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