1

我有一个ItemTemplate包含两个文本框的转发器控件。我遍历中继器并将数据插入到我的数据库中。问题是第一个 TextBox 是唯一插入的。

我在方法中绑定了List 中的第一个TextBox PageLoad

<asp:Repeater ID="questionRepeater" ViewStateMode="Enabled" runat="server">
    <ItemTemplate>
        <tr class="">
            <td>
                <div class="control-group">
                    <label class="control-label">Queston  : </label>

                    <div class="controls">
                        <asp:TextBox runat="server" ID="txtQ" Text='<%#Eval("Question") %>' ReadOnly="true" CssClass="span8">
                        </asp:TextBox>
                    </div>
                </div>
            </td>
        </tr>
        <tr class="info">
            <td>
                <div class="control-group">
                    <label class="control-label">Answer : </label>
                    <div class="controls">
                        <asp:TextBox runat="server" ID="txtAns"
                            Height="150" TextMode="MultiLine" CssClass="span8"></asp:TextBox>

                    </div>
                </div>
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

我背后的代码:

protected void btnSave_Click(object sender, EventArgs e)
{
    Sessions session = new Sessions();
    SessionQuestion sessionQuestions = new SessionQuestion();

    session.ClientId = id;
    session.DateTime = DateTime.Now;
    session.Report = txtReport.Text;
    session.Notes = string.Empty;
    session.IsActive = IsActive.Active;

    int sessionId = SessionBLL.Insert(session);

    foreach (Control item in questionRepeater.Items)
    {
        sessionQuestions.SessionId = sessionId;


        TextBox txtQ = (TextBox)item.FindControl("txtQ");
        sessionQuestions.Answer = "";
        sessionQuestions.Question = txtQ.Text;

        var txtAns = (TextBox)item.FindControl("txtAns") as TextBox;
        if (txtAns != null)
        {
            sessionQuestions.Answer = "";
            sessionQuestions.Answer = txtAns.Text; 
        }


        Thread.Sleep(150);
        if (txtAns != null && txtQ.Text != null)
        {
            SessionQuestionBLL.Insert(sessionQuestions);
        }
    }

    string message = "";

    Response.Redirect("/Sessions/Sessions.aspx?message=" + message);
}
4

1 回答 1

1

也许那是因为您没有在 Page_Load 中包含转发器数据绑定

If (!IsPostBack)
{
    // Databind your repeater
}

此外,当您遍历中继器时,最好遍历 item & Alternative 类型的项目,如下所示

foreach (RepeaterItem item in questionRepeater.Items)
{
    if (item.ItemType == ListItemType.Item || 
        item.ItemType == ListItemType.AlternatingItem)
    {
    }
}
于 2013-08-25T14:10:12.593 回答