0

I have a gridview in an ASP.NET site.

There's a TemplateField right now that works fine - this is a survey form, and by default questions are answered using textboxes:

<asp:TemplateField HeaderText="" Visible="True" >
   <ItemTemplate>
      <asp:TextBox ID="txtAnswer" Text='<%# Bind("Answer") %>' runat="server" 
       TextMode="MultiLine" Height="76px" MaxLength="2000" Width="377px">
       </asp:TextBox>
    </ItemTemplate>
 <EditItemTemplate>
       <asp:TextBox ID="txtAnswer" Text='<%# Bind("Answer") %>' runat="server" 
       TextMode="MultiLine" Height="76px" MaxLength="2000" Width="377px">
       </asp:TextBox>
 </EditItemTemplate>
 </asp:TemplateField>

The requirement is to now add new questions that may be answered by dropdownlists. I've got an idea on how to do this (passing the question number into a function and checking for the presence of dropdown answers that are stored in another table), but I'm struggling with dynamically updating the templatefield based on the question type...any suggestions?

UPDATE

I managed to get this partially working through a helper function. (Probably not my best code, but it's almost getting the job done) The thing is I get a string that's telling me the type in my output instead of the actual controls (Textboxes or dropdownlists, respectively)...how can I correct that?

  public Control GetAnswerControl(string QuestionID, string Answer)
{
    List<ListItem> lstOptions = new List<ListItem>();

    SqlCommand cmd = new SqlCommand("pDropDownAnswers_Get", functions.NewSupplierRequest);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@QuestionID", SqlDbType.Int);
    cmd.Parameters["@QuestionID"].Value = Int32.Parse(QuestionID);

    try
    {
        functions.NewSupplierRequest.Open();
        SqlDataReader r = cmd.ExecuteReader();
        while (r.Read())
        {
            lstOptions.Add(new ListItem(r["DropDownAnswer"].ToString(), r["DropDownAnswer"].ToString()));
        }
    }
    catch (Exception err)
    {
        this.lblError.Text = err.Message;
    }
    finally
    {
        functions.NewSupplierRequest.Close();
    }

    if (lstOptions.Count == 0)
    {
        TextBox tb = new TextBox();
        tb.ID = "txtAnswer";
        tb.Text = Answer;
        tb.TextMode = TextBoxMode.MultiLine;
        tb.Height = 76;
        tb.Width = 377;
        tb.MaxLength = 2000;

        return tb;
    }
    else
    {
        DropDownList dl = new DropDownList();
        dl.DataSource = lstOptions;
        dl.DataBind();
        dl.SelectedValue = Answer;
        return dl;
    }
}
4

1 に答える 1

0

私はこれを別のアプローチで機能させることにしました...

  1. まず、グリッドビューにいくつかの非表示フィールドとプレースホルダーを設定して、質問IDと回答IDを保持します
  2. 次に、グリッドビューの行をループしてIDを取得し、非表示のフィールドから回答するヘルパー関数を作成しました。
  3. コードビハインドからプレースホルダーにコントロールを追加すると、実際には、取得した文字列ではなく、コントロールとしてフォーマットされます。
于 2012-12-12T19:05:31.183 に答える