2013-07-04 16 views
0

IDE:Microsoft Visual Studio 2012,DBMS:Microsoft SQL Server 2012如何使用登錄鍵將標籤中的文本設置爲數據庫中的名稱?

我有2個ASP.NET網頁,一個登錄頁面和主頁面。我想要做的是在登錄後,它會將ID保存到會話中,然後使用它從數據庫(與ID相同的表)檢索用戶的名字並將其轉換爲主頁上的標籤。我用能做到這一點,在過去:

SqlDataReader 

但現在我有一個數據訪問層類,它返回一個:

DataTable 

有我的問題。我似乎無法弄清楚如何去做。到目前爲止,我有這些作品:

Session.Add("StudentID", dt); 

這是爲登錄頁面。下面是主頁:

DataTable dt = (DataTable)Session["StudentUser"]; 
int ID = int.Parse(Session["StudentID"].ToString()); 
DAL.GetData("SELECT Fname FROM StudentUser WHERE StudentID = " + ID); 
lblName.Text = dt["Fname"].ToString(); 

至於我的DAL代碼,在這裏,他們是:

public static DataTable GetData(string sql) 
{ 
     SqlConnection con = new SqlConnection(DAL.ConnectionString); 
     con.Open(); 
     SqlCommand com = new SqlCommand(sql, con); 
     SqlDataAdapter da = new SqlDataAdapter(com); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 
     return dt; 
} 

我的表稱爲StudentUser並在標籤上我想要的部分是Fname

當使用SqlDataReader(dr)登錄的代碼通常如下所示:

Session.Add("StudentID", dr["StudentID"].ToString()); 

而對於主頁:

int ID = int.Parse(Session["StudentID"].ToString()); 
SqlCommand com = new SqlCommand("SELECT Fname FROM StudentUser WHERE StudentID = " + ID, con); 
SqlDataReader dr = com.ExecuteReader(); 
dr.Read(); 
lblName.Text = dr["Fname"].ToString(); 
dr.Close(); 

SqlDataReader代碼的工作,但我決心儘可能使用我的數據訪問層,即使它會導致我使用,我不熟悉的代碼。請幫助親愛的人。 :)

+0

你的登錄代碼是什麼樣的? – DGibbs

+0

@DGibbs 登錄按鈕代碼: ... DataTable dt = DAL.GetData(「SELECT * FROM StudentUser WHERE StudentID =」+ txtID.Text); ...一些錯誤檢查代碼... if(txtPW。Text == dt.Rows [0] [1] .ToString()); Session.Add(「StudentID」,dt);的Response.Redirect( 「ApplyBlueform.aspx」); } –

回答

0

問題是你不能使用一種方法的所有可能性。在你的例子中,你沒有辦法向你的dal發送一個參數,這意味着你必須在你的dal中創建一個這樣的方法。

我有一個或多或少做你想要的類。這不是一個適當的存儲庫,但對於初學者,它可能有你需要的。

http://pastebin.com/xYhsSeXW

+0

您的建議非常有效。我在我的數據訪問層上創建了一個返回SqlDataReader值的新方法。將這種新創建的方法插入網頁代碼中,然後進行一些編碼,然後在標籤中顯示第一個名稱。謝謝大家的幫忙,歡呼! :) –

0

你調用方法DAL.GetData,但你不保存任何地方DataTable ..,你爲什麼不試試這個:

DataTable dt1 = DAL.GetData("SELECT Fname FROM StudentUser WHERE StudentID = " + ID); 
lblName.Text = dt1["Fname"].ToString(); 

相反的:

DAL.GetData("SELECT Fname FROM StudentUser WHERE StudentID = " + ID); 
lblName.Text = dt["Fname"].ToString(); 

您需要存儲從您創建的方法返回的值,否則調用該方法沒有意義。

+0

這給了我一個錯誤:「無法將索引與[]應用於類型'System.Data.DataTable'的表達式」 –

相關問題