2013-12-23 76 views
-1

我有一個gridview下拉,所以當gridview加載和下拉列表綁定然後下拉列表只顯示下拉列表的第一個值,它是沒有顯示以前選擇的值。當gridview加載時,我希望下拉列表顯示之前爲該行選擇的內容。這裏是我的代碼: ASPX標記爲下拉:DropDown選中的值不顯示

<asp:TemplateField HeaderText="Answer"> 
    <ItemTemplate> 
     <asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label> 
     <asp:DropDownList ID="ddl_Answer" runat="server"> 
     </asp:DropDownList> 
    </ItemTemplate> 

這裏是後面的代碼:

protected void RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     DropDownList ddl_Answer; 
     //get current index selected 
     int current_quest = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value); 
     ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList; 
     using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString)) 
     { 
      con2.Open(); 
      using (SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from table1 where ID= '" + current_quest + "' ", con2)) 
      { 
       ddl_Answer.DataSource = cmd1.ExecuteReader(); 
       ddl_Answer.DataTextField = "DD_ANSWER"; 
       ddl_Answer.DataValueField = "DD_ANSWER"; 
       ddl_Answer.DataBind();       
      } 
       con2.Close(); 
     } 

    } 

我曾嘗試結合後添加此行的代碼,但我得到這個錯誤「對象引用不設置爲一個對象」的一個實例

ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true; 

感謝

+1

我想你的if語句結尾缺少一個括號? –

+0

將最後一行分隔成多行,並使用調試器逐步執行每一行。 –

+0

謝謝,但這是問題,我只是忘了添加支架,當我粘貼代碼 – moe

回答

1

我相信,在你的SELECT你需要使用current_quest_sk代替current_quest

ASLO嘗試檢查空訪問您的控件之前:

var ddl_Answer = e.Row.FindControl("ddl_Answer") as DropDownList; 
var answerLabel = e.Row.FindControl("lblAns") as Label; 
if(answerLabel !=null && ddl_Answer!=null) 
{ 
    ddl_Answer.Items.FindByValue(answerLabel.Text).Selected = true; 
} 


@afzalulh有如果 current_quest_sk有效點刪除報價(ID)是表中的整數。

你應該避免SQL注入,但這是一個不同的話題。

+1

失敗+1 - 我只是輸入這個答案!另外,ID可能是整數,所以OP應該在select語句中移除''''。 – afzalulh

0

播在你的代碼中創建一個斷點,然後用你的調試器進行設置。

要麼你有你的字符串名稱中的拼寫錯誤,要麼你正在查看錯誤的控件。

單步執行代碼將幫助您確切地看到代碼的哪一行導致問題。

你也可以在整個事情上放一個try/catch塊來幫助你隔離問題。一旦發現問題,請移除try/catch塊。

+0

我已經嘗試過,它仍然在代碼行 – moe