2016-05-30 23 views
1

我想要做的是在我的數據庫中獲取一個特定的列。目前我有ID,用戶名,姓氏,名字,電子郵件,CreditRequest和聯繫人。我想要在我的asp文本框中顯示信用請求列。你可以分享的任何技巧?在sql中顯示一個特定的列到一個文本框asp.net

我在想是這樣的:

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True")) 
{ 
    scn.Open(); 
    SqlCommand cmd = new SqlCommand("SELECT CreditRequest FROM CreditRequests WHERE [email protected]", scn); 
+0

您只需要執行該命令,取回結果並更新文本框的文本屬性。 – Steve

+0

hi @Steve你介意給我一個樣本代碼嗎?尤其對於像我這樣的初學者來說,將會非常感激。 :) –

回答

0

您需要到執行該命令的方法適當調用來完成你的代碼,並取回結果。我想這個查詢只返回一條記錄,所以調用ExecuteScalar非常有效。

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True")) 
{ 
    scn.Open(); 
    SqlCommand cmd = new SqlCommand("SELECT CreditRequest FROM CreditRequests WHERE [email protected]", scn); 

    // Add the parameter required by the query.... 
    cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = variableWithYouUserNameValue; 

    // Run the query and get the single row/column returned 
    object value = cmd.ExecuteScalar(); 

    // If it is not null (possible if the where fails) then put on textbox 
    if(value != null) 
     txtBoxCredit.Text = value.ToString(); 
} 

當然,我不知道你的文本框的真實姓名,所以我選擇了一個虛構的名字,你的文本框的真實姓名更改。對於包含當前用戶名搜索的變量也是如此。

+0

非常感謝史蒂夫。 –

+0

那麼,您正在搜索用戶的數據_WHERE Username = @ Username_因此,在您的應用程序中,在達到這一點之前,您應該已經收集UserName值作爲參數傳遞給查詢。這應該是某種你已經定義並從某種輸入中讀取的字符串變量 – Steve

+0

是的,我已經鍵入Session [「New」],它現在工作:) –

相關問題