2012-04-26 22 views
0

我正在使用visual studio 2010,並添加了一個數據庫並使用SQLdatasource連接到它。我正在創建一個基本的登錄。我希望用戶輸入登錄名,當他嘗試登錄時,我想通過數據庫進行交互並檢查登錄名是否存在。 我將如何從數據庫中選擇一列並對其進行迭代。使用SQLdatasource驗證 - C#

我想選擇SQL語句會從tblUser

SELECT名其中,用戶名是列,tblUser是表

回答

1

你得到的SQL語句的權利,在結束你的SQLDataSource看起來像這樣:

<asp:SqlDataSource 
      id="SqlDataSource1" 
      runat="server" 
      DataSourceMode="DataReader" 
      ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;" 
      SelectCommand="SELECT userName from tblUser"> 
     </asp:SqlDataSource> 

注意:您可能需要使用位於您的配置文件中的連接字符串:

ConnectionString="<%$ ConnectionStrings:MyNorthwind%>" 

此外,你也可以嘗試沒有,因爲它聽起來像是你將不會被綁定的結果通過一個SqlDataSource來執行這個查詢控制。例如:

using (SqlConnection connection = new SqlConnection(
       connectionString)) 
    { 
     SqlCommand command = new SqlCommand(
      "SELECT userName from tblUser", connection); 
     connection.Open(); 
     SqlDataReader reader = command.ExecuteReader(); 
     try 
     { 
      while (reader.Read()) 
      { 
       // check if reader[0] has the name you are looking for 

      } 
     } 
     finally 
     { 
      // Always call Close when done reading. 
      reader.Close(); 
     } 
    } 
+0

非常感謝。我如何使用SQLDatasource來做到這一點?我們有select語句,你將如何使用Select語句遍歷數據庫? – user1005253 2012-04-26 02:01:18

+0

執行SQLDatasource控件的Select方法並迭代返回的數據視圖對象。看到這個頁面的更多細節:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.select.aspx – Ulises 2012-04-26 02:03:52

+0

乾杯。像這樣? 'DataView dv =(DataView)SqlDataSource3.Select(DataSourceSelectArguments.Empty); ((dv!= null)&&(dv.Count> 0)) DataRow dvUserInfo = dv.Table.Rows [0]; login_txtb.Text.CompareTo(dvUserInfo [「userName」]。ToString()); }' – user1005253 2012-04-26 02:18:40