2012-02-27 115 views
0

我一直在使用這種編碼,就像一週前一樣。但是我被卡在檢索部分。所以,我有這8個文本框用於支出,每個支出8個以上的價格。在該頁面上,有一個下拉菜單,用戶將選擇月份,然後選擇當月的費用,例如1月份,文本框將顯示該月份的數據庫記錄。如何鏈接月份,以便它可以根據用戶的記錄從數據庫中檢索數據?以及如何僅顯示當前登錄用戶的記錄?謝謝你幫我。從sql檢索數據

protected void Button1_Click(object sender, EventArgs e) 
{ 
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString); 
    conn.Open(); 
    SqlCommand cmd = new SqlCommand("SELECT * FROM ExpTab WHERE UserID = @UserName and month = @month", conn); 
    cmd.Parameters.Add(new SqlParameter("UserName", HttpContext.Current.User.Identity.Name)); 
    cmd.Parameters.Add(new SqlParameter("@month", DropDownList2.SelectedValue)); 
    DataTable dt = new DataTable(); 

只想問你,如何在文本框中顯示檢索到的數據? Thankk你

+0

你的數據庫是否有任何日期列? – 2012-02-27 05:36:20

+1

我認爲它更好,如果你的數據庫架構以及 – Jayanga 2012-02-27 05:37:47

+0

你有沒有試過調試它?它返回什麼?用戶SQL分析器 – 2012-02-27 05:41:03

回答

1

假設用戶選擇從下拉列表中,而不是日曆控件月,你會做這樣的事情:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings ["Connection"].ConnectionString)) 
    { 
     conn.Open(); //you were missing this 
     SqlCommand cmd = new SqlCommand("SELECT * FROM ExpTab WHERE UserID = @UserName and month(date_column)[email protected]", conn); 
     cmd.Parameters.Add(new SqlParameter("UserName", 
     HttpContext.Current.User.Identity.Name)); 
     cmd.Parameters.Add(new SqlParameter("@month", dropDownDate.SelectedValue)); 
     DataTable dt = new DataTable(); 
     dt.Load(cmd.ExecuteReader());//load the data in a data table, for example. 
    } 
} 

上面代碼中作以下假設:

  1. 你在包含日期時間的ExpTab表中有一列;因此這樣的:... and month(date_col)將匹配你感興趣的月份的數字
  2. 您月份選擇來自一個叫做dropDownDate下拉式選單,每個月分配從1到12
  3. 一個整數值,我的代碼不會考慮。年。我會讓你弄清楚那一部分。

鏈接到MONTH function文檔。

+0

嗨,我快到了。只是想問你,如何在文本框中加載數據?謝謝 – 2012-02-27 06:32:30

+0

只需遍歷DataTable變量(dt)的行即可。使用以下foreach循環:* foreach(dt.Rows中的DataRow行)... *然後將數據行的特定列中的值分配給txtfield。 – Icarus 2012-02-27 12:30:39