我的下拉框没有保留所选的值,所以我不得不添加这行代码:
ddl_Answer.Items.FindByValue((e.Row.FindControl("lblAns") as Label).Text).Selected = true;
但是添加这行代码会导致另一个问题。我在Gridview中构建了下拉列表并且Gridview有一个Edit链接,一旦你点击编辑然后你应该看到下拉框,但现在的问题是当我点击编辑链接并且在下拉列表中没有选择任何内容我收到一个错误。它只适用于已经选择的东西。这是我的代码:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
int current_quest_sk = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
DropDownList ddl_Answer = (DropDownList)e.Row.FindControl("ddl_Answer");
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection con2 = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd1 = new SqlCommand("select distinct DD_ANSWER from MainTable D, SecondryTable Q where Q.ANS_OPT = D.ID and QUEST_SK= '" + current_quest_sk + "' ");
cmd1.Connection = con2;
con2.Open();
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;
}
这是下拉列表的标记
<asp:GridView ID="GridView1" runat="server" Width="870px" OnRowDataBound="RowDataBound"
AutoGenerateColumns="False" Font-Names="Arial" Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B"
HeaderStyle-BackColor="green" AllowPaging="True" ShowFooter="True" OnPageIndexChanging="OnPaging"
OnRowEditing="EditGridView1" OnRowUpdating="UpdateGridView1" OnRowCancelingEdit="CancelEdit"
CellPadding="4" BackColor="White" BorderColor="#336666"
BorderStyle="Double" BorderWidth="3px"
DataKeyNames="QUEST_SK">
<AlternatingRowStyle BackColor="#C2D69B" />
<Columns>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" >
<ItemStyle Font-Size="Smaller" ForeColor="#FF3300" />
</asp:CommandField>
</Columns>