ASP.NET How to bind data in DropDownList outside GridView? - c#

I am creating a web aplication to access data in a SQL Server 2008 database. I show the data in a Gridview and I can succesfully edit the rows (even with DropDownLists), but I want to implement the edit of those records with a modal dialog/popup using Bootstrap.
However, I can not get working these DropDownLists in this modal, because resides in a DIV outside the <asp:GridView> element. I can bind others text fields in the modal dialog, with this code (the modal dialog is fired with a command ) [code_behind]:
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtRUT.Text = HttpUtility.HtmlDecode(gvrow.Cells[2].Text);//.ToString();
txtDIGITO.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text);
txtCOD_FISA.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);
txtNOMBRE.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text);
//ddlCARGO is the DropDownList
ddlCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[6].Text);
lblResult.Visible = false;
//I know that the DropDownList ist outside the GridView, but i don't know how to access/bind data to it
DropDownList combo_cargo = GridView2.Rows[index].FindControl("ddlCARGO") as DropDownList;
if (combo_cargo != null)
{
combo_cargo.DataSource = DataAccess.GetAllCargos(); //in GridView default edit mode, this works OK
combo_cargo.DataTextField = "cargo";
combo_cargo.DataValueField = "idCARGO";
combo_cargo.DataBind();
}
combo_cargo.SelectedValue = Convert.ToString(HttpUtility.HtmlDecode(gvrow.Cells[6].Text));
}
The modal html code [.aspx]:
<!-- EDIT Modal Starts here -->
<div id="editModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="editModalLabel">Editar Empleado</h3>
</div>
<asp:UpdatePanel ID="upEdit" runat="server">
<ContentTemplate>
<div class="modal-body">
<p> Nombre: <asp:TextBox ID="txtNOMBRE" runat="server" columns="40"></asp:TextBox> </p>
<p>RUT: <asp:TextBox ID="txtRUT" runat="server" columns="8"></asp:TextBox> -
<asp:TextBox ID="txtDIGITO" runat="server" columns="1"></asp:TextBox></p>
<p>Código Fisa: <asp:TextBox ID="txtCOD_FISA" runat="server" columns="7"></asp:TextBox></p>
<%--<p>Cargo: <asp:TextBox ID="txtCARGO" runat="server" columns="7"></asp:TextBox></p>--%>
<p>Cargo: <asp:DropDownList ID="ddlCARGO" runat="server"></asp:DropDownList></p>
<%-- <p>Estado: <asp:TemplateField HeaderText="ESTADO" SortExpression="idESTADO">
<EditItemTemplate>
<asp:DropDownList ID="ddlESTADO" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblESTADO" runat="server" Text='<%# Bind("ESTADO") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField> </p> --%>
</div>
<div class="modal-footer">
<asp:Label ID="lblResult" Visible="false" runat="server"></asp:Label>
<asp:Button ID="btnSave" runat="server" Text="Update" CssClass="btn btn-info" OnClick="btnSave_Click" />
<button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView2" EventName="RowCommand" />
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
<!-- Edit Modal Ends here -->

I can give you an idea.
Create a DIV/user control with those controls that you need to edit.
On ROW click - open the DIV in model (jq you can use) and then either pass the Row content to the Model.open Or pass some unique ID of that ROW and load again from DB the Row corresponding detail. And allow editing there and on Save over there - saving to DB with that unique ID preserved.
Let us know

Finally I have found the solution:
Modal html (.aspx):
<div class="form-group">
<asp:TextBox ID="txtCARGO" runat="server" CssClass="hiddencol"></asp:TextBox> <%--data value field (hidden with CSS)--%>
<label class="col-xs-3 control-label" for="editModalCargo">Cargo</label>
<div class="col-xs-3 input_medio">
<asp:DropDownList id="editModalCargo" runat="server" name="editModalCargo" class="form-control input-md"/> <%--data text field--%>
</div>
</div>
<div class="form-group hiddencol"> <%--field with row id (hidden with CSS)--%>
<asp:TextBox ID="txtID" runat="server" columns="2"></asp:TextBox>
</div>
I've put OnRowCommand="GridView2_RowCommand" on <asp:GridView> and created a <asp:ButtonField> with CommandName="editRecord"> to edit the row.
Code behind (.aspx.cs):
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtID.Text = HttpUtility.HtmlDecode(gvrow.Cells[17].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtID">
txtCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[13].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtCARGO">
lblResult.Visible = false;
BindEditCargo(txtCARGO.Text);
}
}
private void BindEditCargo(string cargoValue) //Populates <asp:DropDownList id="editModalCargo">
{
editModalCargo.DataSource = DataAccess.GetAllCargos();
editModalCargo.DataTextField = "cargo";
editModalCargo.DataValueField = "idCARGO";
// Bind the data to the control.
editModalCargo.DataBind();
// Set the default selected item, if desired.
editModalCargo.SelectedValue = cargoValue;
}
DataAccess.cs:
public static DataTable GetAllCargos()
{
DataTable dt = new DataTable();
string sql = #"SELECT * FROM CARGO";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BRconn"].ToString()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
return dt;
}
To read the value from modal (to pass it to a Update query for example), you can use (in code behind):
protected void btnSave_Click(object sender, EventArgs e) // Handles Update Button Click Event
{
int idEMPLEADO = Convert.ToInt32(txtID.Text); //Read value from <asp:TextBox ID="txtID">
int idCARGO = Convert.ToInt32(editModalCargo.SelectedValue); //Read value from <asp:DropDownList id="editModalCargo">
DataAccess.UpdateEmpleado(idEMPLEADO, idCARGO); //Update Query
BindData(); //Refresh Gridview
}

Related

Issue grabbing correct control/update panel in repeater

I'm having issues with dynamically updating a drop down list control when it is inside a repeater.
Basically I have a repeater and inside that repeater are 2 drop down lists. The one list is defined in my aspx page, the other drop down list is inside an update panel where I want to be able to have it dynamically update based on the selection of the first drop down list. I think part of my problem is the updatepanel is getting confused because I have more than one repeater item?
Here is the code for my repeater:
<asp:Repeater ID="billingTemplate" runat="server" OnItemDataBound="template_ItemDataBound">
<ItemTemplate>
<tr style="font-size: 100%" runat="server">
<td colspan="4" style="width: 100%; vertical-align: top">
<div class="panel panel-default panel-billing">
<asp:Panel CssClass="row panel-heading panel-heading-billing text-left" ID="headingBilling" ClientIDMode="Static" runat="server">
<div class="col-xs-1">
<input type="hidden" id="templateUK" runat="server" value='<%#Eval("templateUK")%>' />
</div>
<div class="col-sm-3">
<label for="ddlInvFilterType" class="col-sm-4 control-label text-right labelCls testclass">Filter Type:</label>
<div class="col-sm-8">
<asp:DropDownList runat="server" ID="ddlInvFilterType" ClientIDMode="Static" placeholder="Choose Filter Type" CssClass="form-control smallSize FilterType" AutoPostBack="true" OnSelectedIndexChanged="ddlFilterType_SelectedIndexChanged">
<asp:ListItem Value="">- None -</asp:ListItem>
<asp:ListItem Value="RevType1">Revenue Type 1</asp:ListItem>
<asp:ListItem Value="RevType2">Revenue Type 2</asp:ListItem>
<asp:ListItem Value="RevType3">Revenue Type 3</asp:ListItem>
<asp:ListItem Value="ServiceTeams">Service Team</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<asp:UpdatePanel ID="InvFilterValuePanel" ClientIDMode="Static" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<div class="col-sm-3">
<label for="ddlInvFilterValue" class="col-sm-4 control-label text-right labelCls">Filter Value:</label>
<div class="col-sm-8">
<asp:DropDownList runat="server" ID="ddlInvFilterValue" ClientIDMode="Static" placeholder="Choose Filter Value" CssClass="col-sm-6 form-control smallSize">
<asp:ListItem Value="">- None -</asp:ListItem>
</asp:DropDownList>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlInvFilterType" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
<asp:Panel CssClass="panel-collapse collapse" ID="collapseBilling" ClientIDMode="Static" runat="server">
<div class="panel-body">
<table class="table table-condensed table-bordered" style="margin: 0; padding: 0; border-top: none; border-bottom: none; border-left: thin; border-right: thin">
<tbody>
<%-- other controls --%>
</tbody>
</table>
</div>
</asp:Panel>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
Heres the code for my selected index change:
protected void ddlFilterType_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DropDownList ddl = (DropDownList)sender;
string ddlClass = ddl.CssClass;
string[] classes = ddlClass.Split(' ');
string repeaterClass = classes[classes.Length - 1];
string repeaterID = "0";
string appendStr = "";
if (repeaterClass.Contains("templateID"))
{
repeaterID = repeaterClass.Substring(repeaterClass.Length - 1);
appendStr = "_" + repeaterID;
}
foreach (RepeaterItem item in billingTemplate.Items)
{
HtmlInputHidden hidden = item.FindControl("headingBilling").FindControl("templateUK") as HtmlInputHidden;
if (hidden.Value == repeaterID)
{
DropDownList d1 = item.FindControl("headingBilling").FindControl("ddlInvFilterType") as DropDownList;
DropDownList d2 = item.FindControl("headingBilling").FindControl("ddlInvFilterValue") as DropDownList;
if (d1.SelectedValue.Length > 0)
{
d2.Items.Clear();
d2.Items.Add(new ListItem(" - None - ", ""));
switch (d1.SelectedValue)
{
case "ServiceTeams":
foreach (var pair in serviceTeamsController.GetAllServiceTeamsLOVs())
{
if (!String.IsNullOrWhiteSpace(pair.Value))
d2.Items.Add(new ListItem(pair.Value, pair.Key));
}
break;
default:
foreach (var pair in masterController.GetMasterLOVs(filterTypeDict[d1.SelectedValue]))
{
if (!String.IsNullOrWhiteSpace(pair.Value))
{
d2.Items.Add(new ListItem(pair.Value, pair.Key));
}
}
break;
}
}
else
{
d2.Items.Clear();
d2.Items.Add(new ListItem(" - None - ", ""));
}
}
}
}
catch (Exception ex)
{
}
}
Heres a screenshot of what I'm looking at when theres more than one repeater item:
Basically whats happening now is if I update the filter type in item2 it will update the filter value in item 1. If I update the filter type in item1 it will update the filter value in item 1 as expected.
What I want is to be able to update item2 filter type and then the filter value in item 2 is updated accordingly.
Anyone have any ideas on what I could be missing?
So ended up getting this to work, I think the main issue was the clientidmode was confusing the update panel somehow, so I removed that and made the update panel go around both drop downs. I also didnt end up needing the trigger so I removed that as well.

ModalPopUp as User Control ASP.NET C#

Im trying build a ModalPopUp as Control. Its have theses controls:
TextBox- placeholder for filter
Button - Search Button
Button - Cancel Button
GridView - To show results
Screen of Search
<ajax:toolkitscriptmanager id="searchPopUp" runat="server"></ajax:toolkitscriptmanager>
<asp:Panel
BackColor="White"
ID="searchPanel"
CssClass="modalPopup"
runat="server"
Style="display: table">
<div class="myContainer">
<uc1:ScreenSearch
runat="server"
ID="mySearch" />
<asp:Button ID="btnToHide" runat="server" Text="Tohide" Style="display: none" />
<asp:Button ID="btnToShow" runat="server" Text="ToShow" Style="display: none" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender
ID="ModalPopUpSearch"
runat="server"
TargetControlID="btnToShow"
PopupControlID="searchPanel"
CancelControlID="btnToHide"
DropShadow="true"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
code behind of : uc1:ScreenSearch
protected void Page_Load(object sender, EventArgs e){...}
protected void fillGridView()
{
myDao dao = new myDao();
DataSet ds = new DataSet();
ds = dao.retornarPesquisa(txtFilter.Text); //return data source
DataTable dt = new DataTable();
gv.DataSource = ds;
gv.DataBind();
}
uc1:ScreenSearch is my control that contain a TextBox, Button(perform search calling the method: fillGridView()) and GridView.
When I try perform the search click Binding the GridView. What the best way to get results in this GridView of my User Control?
You haven't posted any of your code so it's hard to tell why it's not working.Below is a working example which displays a Bootstrap modal popup -> allows a user to search -> displays the results in a GridView inside the modal popup:
Code behind:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
public partial class ModalPopupFromGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
//Use txtSearch.Text to lookup the data you want to bind to the GridView, mine is hardcoded for the sake of simplicity
var p1 = new Person { Name = "Name 1", Surname = "Surname 1" };
var p2 = new Person { Name = "Name 2", Surname = "Surname 2" };
GridView1.DataSource = new List<Person> { p1, p2 };
GridView1.DataBind();
ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "showPopup();", true);
}
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript">
//It'svery important that showPopup() is outside of jQuery document load event
function showPopup() {
$('#myModal').modal('show');
}
$(function () {
$(".show").click(function () {
showPopup();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Show Popup
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Details</h4>
</div>
<div class="modal-body">
<asp:TextBox ID="txtSearch" runat="server">
</asp:TextBox><asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
<br /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Surname" HeaderText="Surname" />
<asp:TemplateField HeaderText="User Details">
<ItemTemplate>
<a class="details" href="#" data-name='<%# Eval("Name") %>' data-surname='<%# Eval("Surname") %>'>Details</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
</body>
Output:
Check if the search buttons autopostback is set to true. Also you will get the event of search button click in gridview_itemchanged event as the search button is inside gridview control. Hope that will work

Textchange event not working

I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the <h3> or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
}
I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(
Just add this script function in your code and in body write onload and call that function.
Javascript:
<script type="text/javascript">
function startProgram() {
setTimeout('errorcheck()', 2000);
}
function errorcheck() {
setTimeout('errorcheck()', 2000);
document.getElementById("NewsTitlePreview").innerText = document.getElementById("Titletxt").value
document.getElementById("NewsContentPreview").innerText = document.getElementById("Contenttxt").value
}
</script>
<body onload="startProgram();">
<form id="form1" runat="server">
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
</body>
You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:
The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.
So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.
Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
<asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.
<script>
$(document).ready(function () {
$('#Titletxt').on('input', function () {
$("#NewsTitlePreview").text($(this).val());
});
$("#Contenttxt").on('input',function () {
$("#NewsContentPreview").text($(this).val());
});
});
</script>
One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}
Try this it will work this how change event call using jquery dont forget to add google apis
<script>
$('#txtbox').change(function() {
alert("change Event");
});
</script>

Repeater loop textbox text is being reported as empty

I'm loading a repeater with data and then on a button click i'm trying to save the data.
Heres what I have but the tbDate.text or tbAmount.texts are always being reported back as "" instead of the values.
<asp:Repeater runat="server" ID="rptInstallments" OnItemDataBound="rptInstallments_ItemDataBound">
<ItemTemplate>
<div class="form-group">
<label class="control-label">Installment Amount</label>
<div class="controls">
<asp:TextBox runat="server" ID="txtAmount" CssClass="form-control"></asp:TextBox>
</div>
</div>
<div class="form-group">
<label class="control-label">Installment Date</label>
<div class="controls">
<asp:TextBox runat="server" ID="txtDate" CssClass="form-control datepicker"></asp:TextBox>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Heres the backend code:
protected void btGo_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in rptInstallments.Items)
{
TextBox tbDate = item.FindControl("txtDate") as TextBox;
TextBox tbAmount = item.FindControl("txtAmount") as TextBox;
String myAmount = tbAmount.Text;
String myDate = tbDate.Text;
var rInstall = dtInstall.NewSubPIDInstallmentsRow();
rInstall.SPID = SPID;
rInstall.InstallmentAmount = Convert.ToDecimal(myAmount);
rInstall.InstallmentDue = Convert.ToDateTime(myDate);
dtInstall.AddSubPIDInstallmentsRow(rInstall);
taInstall.Update(dtInstall);
}
}
EDIT
I'm hacking in the repeater to no real data source. Could this be the problem?
int[] RowCount = new int[numberOfInstallments];
rptInstallments.DataSource = RowCount;
rptInstallments.DataBind();
Add your code of Binding the Repeater control with in the if (!IsPostBack) condition of Page_load. This worked for me.

Error Help::Multiple controls with the same ID 'ctl00' were found. FindControl requires that controls have unique IDs

Getting the above Error.
I want the IDs of the Accordian to be unique everytime it is bound. I added Accordian pane dynamically in my code..Its not working:-
like this :-
for(int i=0;i< dt.Rows.Count;i++)
{
AccordionPane accp = new AccordionPane();
accp.ID = "accp" + i.ToString();
Accordion1.Panes.Add(accp);
Accordion1.DataSource = dt.DefaultView;
Accordion1.DataBind();
}
I want the IDs of the Accordian to be unique. How can I accomplish what I want ?
Aspx Page:-
<div id="div1" runat="server">
<telerik:RadTabStrip ID="RadTabStrip1" runat="server" MultiPageID="RadMultiPage1" OnTabClick="RadTabStrip1_OnTabClick" ClickSelectedTab="true">
</telerik:RadTabStrip>
<br /><br />
<telerik:RadMultiPage ID="RadMultiPage1" runat="server" SelectedIndex="0">
</telerik:RadMultiPage>
</div>
<cc1:Accordion ID="Accordion1" runat="server" FadeTransitions="true" Visible="true" AutoSize="None"
SelectedIndex="0" RequireOpenedPane="false" TransitionDuration="250" HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" CssClass="toggler">
<HeaderTemplate>
<b style="color: Black">
<%#Eval("Ques")%>
</b>
</HeaderTemplate>
<ContentTemplate>
<p> <%#DataBinder.Eval(Container.DataItem, "QuesAns")%></p>
</ContentTemplate>
</cc1:Accordion>
<br />
You shouldn't be calling BindAccordion multiple times because (I'm guessing) that's why you're ending up with multiple controls with the same ID.
You're calling it in both Page_Load and RadTabStrip1_OnTabClick. My best guess from your code is that you should only call it once from Page_Load when !IsPostBack like you have already.
If that doesn't work, try the following:
protected void BindTabStrip()
{
DataSet ds = GetDataSetForTabs();
RadTabStrip1.AppendDataBoundItems = true;
RadTabStrip1.DataSource = ds;
RadTabStrip1.DataTextField = "QuesType";
RadTabStrip1.DataValueField = "QuesTypeID";
RadTabStrip1.DataBind();
// Remove it accordian from the page before adding it to
// a new ControlCollection
Page.Controls.Remove(Accordian1);
RadPageView pv = new RadPageView();
pv.Controls.Add(Accordion1);
RadMultiPage1.PageViews.Add(pv);
}

Categories

Resources