我有一個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;
感謝
我想你的if語句結尾缺少一個括號? –
將最後一行分隔成多行,並使用調試器逐步執行每一行。 –
謝謝,但這是問題,我只是忘了添加支架,當我粘貼代碼 – moe