2013-10-26 23 views
2

看來我的代碼不完整,或者我的語法錯誤,但我盡我所能提出了某種解決方案,但迄今爲止沒有成功......所以這裏是我想要做的: 我有幾個下拉框,並希望將每個下拉框的選定值分配給表適配器中的值。這是到目前爲止我的代碼,但不知道什麼是失蹤:這裏如何在後面的代碼中使用SqlDataAdapter?

protected void Page_Load(object sender, EventArgs e) 
{ 
    ID = Convert.ToInt32(Request.QueryString["myID"]); 
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString); 
    SqlDataAdapter da = new SqlDataAdapter("SELECT NAME, DEPARTMENT, LOCATION from MyTable WHERE ID = '" + ID + "' ", con); 
    DataTable dt= new DataTable(); 
    da.Fill(dt); 

    ddl_Name.SelectedValue = dt[0].Name; 
    ddl_DEPARTMENT.SelectedValue = dt[0].DEPARTMENT; 
    ddl_LOCATION.SelectedValue = dt[0].LOCATION; 
} 

我的問題開始當我鍵入DT [0] .name和似乎當我添加的零它不喜歡。請幫助。感謝

回答

3

dt是沒有索引的DataTable,你想要的DataRow的能量場,所以你需要通過DataTable.Rows[index]先得到該行:

if(dt.Rows.Count > 0) 
{ 
    DataRow row = dt.Rows[0]; 
    ddl_Name.SelectedValue = row.Field<string>("Name"); 
    ddl_DEPARTMENT.SelectedValue = row.Field<string>("DEPARTMENT"); 
    ddl_LOCATION.SelectedValue = row.Field<string>("LOCATION"); 
} 

您不能直接訪問該字段(沒有一個強類型DataTable)。你必須使用DataRow.Field獲得一個字段或舊的弱類型索引值:

object name = row["Name"]; 
  • 除此之外,你不應該使用字符串連接來建立你的SQL查詢。您通過url參數打開sql注入。使用sql參數來防止這種情況。
  • 我假設您使用的是ViewState(默認值),然後將該代碼塊置於!IsPostBack檢查中,否則將不會觸發SelectedIndexChanged事件,因爲用戶選擇將被舊數據庫值覆蓋。

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!IsPostBack) 
    { 
     ID = Convert.ToInt32(Request.QueryString["myID"]); 
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString); 
     SqlDataAdapter da = new SqlDataAdapter("SELECT NAME, DEPARTMENT, LOCATION from MyTable WHERE ID = @ID", con); 
     DataTable dt= new DataTable(); 
     da.SelectCommand.Parameters.AddWithValue("@ID", int.Parse(ID)); 
     da.Fill(dt); 
     // Code above... 
    } 
} 
+0

太感謝你了,你的解決方案的工作,我很欣賞ü教我一些額外的工作人員。 thnks – moe

相關問題