2012-11-05 213 views
1

如果我有一個名爲「car」的類,並且此car類使用SQL查詢來填充ID,名稱,類型,模型,引擎和大小等屬性。如何使用該數據填充asp:formview?填充表單

我嘗試這樣做:

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

,但我不斷收到此錯誤:

​​

任何幫助,將不勝感激!

感謝

+1

一個簡單的方法是使用一個'列表(汽車)'在一個單一的汽車或單'IEnumerable的(汽車)''通過carList.Where(功能(C) c.ID = carID)'。你也可以使用'SqlDataAdapter'來填充'DataTable'和'table.Where(Function(r)r.Field(Of Int32)(「ID」)= carID)''。 –

回答

2

一個簡單的方法是使用一個List(Of Car)在一個單一的汽車或通過carList.Where(Function(c) c.ID = carID)IEnumerable(Car)。您也可以使用SqlDataAdapter填寫DataTabletable.Where(Function(r) r.Field(Of Int32)("ID") = carID)。或者只是選擇從數據庫中單一的汽車,這也是當你不反正需要完整的列表中選擇最efficiant方式:

數據表:

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 [email protected]", 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 [email protected]", 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