2010-04-08 130 views
-1

是否可以使用數據集填充列表視圖?我有一個返回數據集的函數。爲什麼IM問這個是因爲我的SQL是相當複雜的,我不能將其轉換爲一個SqlDataSource ...如何通過數據集填充ASP.NET 3.5中的列表視圖?

Public Function getMessages() As DataSet 
    Dim dSet As DataSet = New DataSet 
    Dim da As SqlDataAdapter 
    Dim cmd As SqlCommand 
    Dim SQL As StringBuilder 
    Dim connStr As StringBuilder = New StringBuilder("") 
    connStr.AppendFormat("server={0};", ConfigurationSettings.AppSettings("USERserver").ToString()) 
    connStr.AppendFormat("database={0};", ConfigurationSettings.AppSettings("USERdb").ToString()) 
    connStr.AppendFormat("uid={0};", ConfigurationSettings.AppSettings("USERuid").ToString()) 
    connStr.AppendFormat("pwd={0};", ConfigurationSettings.AppSettings("USERpwd").ToString()) 
    Dim conn As SqlConnection = New SqlConnection(connStr.ToString()) 
    Try 
     SQL = New StringBuilder 
     cmd = New SqlCommand 
     SQL.Append("SELECT m.MESSAGE_ID, m.SYSTEM_ID, m.DATE_CREATED, m.EXPIRE_DATE, ISNULL(s.SYSTEM_DESC,'ALL SYSTEMS') AS SYSTEM_DESC, m.MESSAGE ") 
     SQL.Append("FROM MESSAGE m ") 
     SQL.Append("LEFT OUTER JOIN [SYSTEM] s ") 
     SQL.Append("ON m.SYSTEM_ID = s.SYSTEM_ID ") 
     SQL.AppendFormat("WHERE m.SYSTEM_ID IN ({0}) ", sSystems) 
     SQL.Append("OR m.SYSTEM_ID is NULL ") 
     SQL.Append("ORDER BY m.DATE_CREATED DESC; ") 

     SQL.Append("SELECT mm.MESSAGE_ID, mm.MODEL_ID, m.MODEL_DESC ") 
     SQL.Append("FROM MESSAGE_MODEL mm ") 
     SQL.Append("JOIN MODEL m ") 
     SQL.Append(" ON m.MODEL_ID = mm.MODEL_ID ") 
     cmd.CommandText = SQL.ToString 
     cmd.Connection = conn 
     da = New SqlDataAdapter(cmd) 
     da.Fill(dSet) 
     dSet.Tables(0).TableName = "BASE" 
     dSet.Tables(1).TableName = "MODEL" 
     Return dSet 
    Catch ev As Exception 
     cLog.EventLog.logError(ev, cmd) 
    Finally 
     'conn.Close() 
    End Try 
End Function 
+2

我有一個給你的提示。查看LINQ和SubSonic。一個存儲過程(SQL Server)甚至可以使這更簡單。 – WVDominick 2010-04-08 14:01:50

+0

給你的另一個提示:你的代碼必須儘可能簡單。不要對你的問題進行調查,人們必須牢記'編輯'你的字符串,認爲連接是正確的,並且所有表格都存在。 – 2010-04-08 15:47:46

回答

1

肯定。在代碼隱藏剛纔設置的數據源的數據表,你要綁定的列表,然後在列表上調用DataBind():

Protected Sub Page_Load(ByVal sender As object, ByVal e As EventArgs) 
    If Not Page.IsPostBack Then 
     Me.LoadData()  
    End If 
End Sub 

Protected Sub LoadData() 
    Dim ds As DataSet = Me.GetData() 
    Me.lstSample.DataSource = ds("Model") 
    Me.lstSample.DataBind() 
End Sub 

(希望這是有效的VB.NET代碼,我通常代碼在C# )。

+0

我會試試這個,謝謝! – 2010-04-08 16:18:16

2

從哪裏開始的這一個...

listview.DataSource = getMessages().Tables(0); 
listview.DataBind;