ahmgeek ahmgeek - 6 months ago 16
SQL Question

TextBox inside a repeater control

I have a repeater control with an

ItemTemplate
containing two Textboxes. I loop through the Repeater and insert the data in my database. The problem is that the first TextBox is the only one inserted.

I bind the first TextBox in the List in the
PageLoad
method.

<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>


My code behind:

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);
}

Answer

Maybe that is because you did not enclose your repeater databinding in your Page_Load

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

Also, when you iterate through the repeater it is better to iterate through items of type item & alternative as shown below

foreach (RepeaterItem item in questionRepeater.Items)
{
    if (item.ItemType == ListItemType.Item || 
        item.ItemType == ListItemType.AlternatingItem)
    {
    }
}
Comments