ASP.NET Repeater control validation causing errors - asp.net

I'm working on an ASP.NET form based application.
I have a repeater bound to database. It has any of the the following controls per row:
RadioButtonList
TextBox
DropDownList
CheckBoxList
There are one of the following validation controls per row:
RequiredFieldValidator
CustomValidator
I have a button outside the repeater. When I click on save button, the code will loop through each repeater item, read selected data and saves it in database.
The problem I'm facing is as soon as I click on save button, it gives me error:
The ControlToValidate property of 'reqValidator' cannot be blank.
I made sure that repeater is loaded for the first time only and not when the page is posted back.
Also, the code in save button does not seem to be executed. Here is my code:
<cms:CMSUpdatePanel runat="server" ID="updatePanelCampaignQuestions">
<ContentTemplate>
<asp:Repeater ID="repeaterQuestions" runat="server" OnItemDataBound="repeaterQuestions_ItemDataBound">
<ItemTemplate>
<div class="repeater-container">
<asp:Label ID="lbQuestion" runat="server" Text='<%# Eval("Question") %>' />
<asp:Label ID="lbQuestionType" runat="server" Text='<%# Eval("QuestionType") %>' Style="display: inline; visibility: hidden" />
<asp:Label ID="lbAnswers" runat="server" Text='<%# Eval("Answers") %>' Style="display: inline; visibility: hidden" />
<asp:Label ID="lbArticleCampaignQuestionID" runat="server" Text='<%# Eval("ArticleCampaignQuestionID") %>' Style="display: inline; visibility: hidden" />
<div class="row validation-container">
<div class="col-md-12 col-lg-12">
<asp:TextBox ID="txtAnswer" CssClass="form-control" runat="server" TextMode="MultiLine" Rows="2" ValidationGroup="Campaign"></asp:TextBox>
<asp:RadioButtonList ID="rdAnswer" runat="server"></asp:RadioButtonList>
<asp:DropDownList ID="ddnAnswer" runat="server"></asp:DropDownList>
<asp:CheckBoxList ID="chkAnswer" CssClass="chkAnswer" runat="server"></asp:CheckBoxList>
<asp:RequiredFieldValidator ID="reqValidator" runat="server" Display="Dynamic" Style="color: #f00" />
<asp:CustomValidator ID="customValidator" runat="server" ClientValidationFunction="checkAnswer" Display="Dynamic" Style="color: #f00" />
<hr />
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
The code for repeater OnItemDataBound:
protected void repeaterQuestions_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string questionType = (e.Item.FindControl("lbQuestionType") as Label).Text;
RequiredFieldValidator reqValidator = (RequiredFieldValidator)e.Item.FindControl("reqValidator");
CustomValidator customValidator = (CustomValidator)e.Item.FindControl("customValidator");
if (questionType.ToLower().Equals("text"))
{
e.Item.FindControl("txtAnswer").Visible = true;
e.Item.FindControl("rdAnswer").Visible = false;
e.Item.FindControl("chkAnswer").Visible = false;
e.Item.FindControl("ddnAnswer").Visible = false;
reqValidator.ControlToValidate = e.Item.FindControl("txtAnswer").ID;
reqValidator.ErrorMessage = "Please fill the answer";
e.Item.Controls.Remove(customValidator);
}
else if (questionType.ToLower().Equals("single selection"))
{
e.Item.FindControl("txtAnswer").Visible = false;
e.Item.FindControl("rdAnswer").Visible = true;
e.Item.FindControl("chkAnswer").Visible = false;
e.Item.FindControl("ddnAnswer").Visible = false;
string strAnswers = (e.Item.FindControl("lbAnswers") as Label).Text;
string[] answers = strAnswers.Split(new[] { "##" }, StringSplitOptions.None);
foreach(string answer in answers)
{
(e.Item.FindControl("rdAnswer") as RadioButtonList).Items.Add(answer);
}
reqValidator.ControlToValidate = e.Item.FindControl("rdAnswer").ID;
reqValidator.ErrorMessage = "Please select one";
e.Item.Controls.Remove(customValidator);
}
else if (questionType.ToLower().Equals("drop down"))
{
e.Item.FindControl("txtAnswer").Visible = false;
e.Item.FindControl("rdAnswer").Visible = false;
e.Item.FindControl("chkAnswer").Visible = false;
e.Item.FindControl("ddnAnswer").Visible = true;
string strAnswers = (e.Item.FindControl("lbAnswers") as Label).Text;
string[] answers = strAnswers.Split(new[] { "##" }, StringSplitOptions.None);
(e.Item.FindControl("ddnAnswer") as DropDownList).Items.Add(new ListItem("- Please Select -", "0"));
foreach (string answer in answers)
{
(e.Item.FindControl("ddnAnswer") as DropDownList).Items.Add(answer);
}
reqValidator.InitialValue = "0";
reqValidator.ControlToValidate = e.Item.FindControl("ddnAnswer").ID;
reqValidator.ErrorMessage = "Please select one";
e.Item.Controls.Remove(customValidator);
}
else if (questionType.ToLower().Equals("multiple selection"))
{
e.Item.FindControl("txtAnswer").Visible = false;
e.Item.FindControl("rdAnswer").Visible = false;
e.Item.FindControl("chkAnswer").Visible = true;
e.Item.FindControl("ddnAnswer").Visible = false;
string strAnswers = (e.Item.FindControl("lbAnswers") as Label).Text;
string[] answers = strAnswers.Split(new[] { "##" }, StringSplitOptions.None);
foreach (string answer in answers)
{
(e.Item.FindControl("chkAnswer") as CheckBoxList).Items.Add(answer);
}
e.Item.Controls.Remove(reqValidator);
customValidator.ErrorMessage = "Please select at least one";
}
}
}
The code for save button:
private void SaveAnswer()
{
int userID = GetUserID();
int campaignID = GetCampaignID();
foreach (RepeaterItem item in repeaterQuestions.Items)
{
string answer = "";
string questionType = (item.FindControl("lbQuestionType") as Label).Text;
int articleCampaignQuestionID = int.Parse((item.FindControl("lbArticleCampaignQuestionID") as Label).Text);
if (questionType.ToLower().Equals("text"))
{
answer = (item.FindControl("txtAnswer") as TextBox).Text;
}
else if (questionType.ToLower().Equals("single selection"))
{
answer = (item.FindControl("rdAnswer") as RadioButtonList).SelectedItem.Text;
}
else if (questionType.ToLower().Equals("drop down"))
{
answer = (item.FindControl("ddnAnswer") as DropDownList).SelectedItem.Text;
}
else if (questionType.ToLower().Equals("multiple selection"))
{
CheckBoxList answerList = (item.FindControl("chkAnswer") as CheckBoxList);
foreach (ListItem checkItem in answerList.Items)
{
if (checkItem.Selected)
{
answer += checkItem.Text + "##";
}
}
if (answer.EndsWith("##"))
answer = answer.Substring(0, answer.Length - 2);
}
// save value of answer to database
}
I'm stuck on this for a very long time now. There is no other exception on the page other than the one mentioned above.
Edit
What is the flow of page postback?
Click on btnSaveAnswer , code for button executes , repeater is reloaded
Or
Click on btnSaveAnswer, repeater is reloaded , code for button executes
If I put repeater binding with:
if(!Page.IsPostBack)
I get the required field validator error
and
if I don't use above if, then I cannot read values from controls in repeater

I figured out the problem in my code. Here is what I did:
Since my repeater is being built dynamically, I'm binding repeater every time and not using Page.IsPostBack
Instead of binding repeater in Page_Load, I'm binding in Page_Init
This fixed my issue

Related

Custom validator message not displaying

VS2013, WebForms, .NET 4.51
I have a FormView defined and in my EditTemplate I have as follows:
<div class="form-group">
<asp:Label ID="lblClientClassification" CssClass="col-md-2 control-label" runat="server" for="cblClientClassifications" Text="Kind"></asp:Label>
<div class="col-md-5">
<asp:CheckBoxList ID="cblClientClassifications" runat="server"></asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="XXXX" ValidationGroup="Default" OnServerValidate="cfvClientClassifications_OnServerValidate"></asp:CustomValidator>
</div>
and then in the code behind:
protected void cfvClientClassifications_OnServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
The OnServerValidate is firing and I am getting to set the validator to invalid as well as setting the error message (Page.IsValid is also false as expected). However, the error text is not displaying. When I view the page source I see:
<span id="ctl00_cphMainContent_fvData_cfvClientKinds" class="label label-danger" style="display:none;">XXXX</span>
instead of the error message I set as well as the fact that it is not visible.
Has anyone got any pointers here on how to track this down? I have looked at similar questions of SO but none of the comments seem to apply. Is this related to FormView perhaps?
Try your control without the CssClass="label label-danger" bootstrap first, and use the code below to check your boxes:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cfvClientKinds.ErrorMessage = "Hey! this is a new message";
}
and I guess you call this line before you fire the above event:
protected void btnValidate_Click(object sender, EventArgs e)
{
Page.Validate();
}
In Short, I think that your problem is either related to your way of finding cblClientClassifications checkBoxList or other code that you haven't stated above.
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
I decided to try out your case and created a new webform added formview and bind it to northwind categories table then inside edititemtemplate I added a checkboxlist and populated it manually. added CustomValidator double clicked it copied your codebehind and it works for me except for the findcontrol part: GuiClientClassificationsFind();
Here is the formview:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1">
<EditItemTemplate>
...
<asp:CheckBoxList ID="cblClientClassifications" runat="server">
<asp:ListItem>Bir</asp:ListItem>
<asp:ListItem>iki</asp:ListItem>
<asp:ListItem>Üç</asp:ListItem>
<asp:ListItem>Dört</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="CustomValidator" OnServerValidate="cfvClientKinds_ServerValidate"></asp:CustomValidator>
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:FormView>
And codebehind with your code:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
I Ali Shahrokhi's method is shorter and works as well as yours..
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
if you check as you entered edititemtemplate in formview you'll see before submitting that your customvalidators span will be there just as you mentioned that's because server hasn't sent it to the client yet somehow.

Why do I have to click a button twice in an ASP.NET repeater to get the command to fire?

I have an ASP.NET page with the following 3 main areas:
1 - list of checkboxes on the left for fitlering results
2 - Repeater that displays the matching results in the middle (with a button for each item)
3 - Repeater that displays the selected items on the right
On initial page load the page will show the data bound checkboxes and will show all results (since nothing has been checked in the filters). As the user checks or unchecks the checkboxes, the page will reload and the matching results will change. So far this part works great.
In the Results Repeater, each item has a Button. When the user clicks the button for an item in the Results the idea is that the item will get added to the Selected Repeater on the right. What is happening is that after I check or uncheck filter checkboxes - the first time that I then try and click on the buttons in the Results repeater, nothing happens. The page just reloads. Then if I click the button a second time, the Repeater Command will fire and the item will get added to the Repeater on the right hand side. Then, as long as I don't change any of the checkboxes I can click on one of the command buttons and it will work right away. But if I check one of the checkboxes in the filters area (which causes the Results to get re-bound) then I have to click one of the buttons twice to get it to fire.
I have a sense that this has something to do with ViewState but I have no idea. Does anyone know why this would be happening?
Below is my code for both the ASPX page and the code behind.
ASPX Code:
<h3>Filters</h3>
<asp:Repeater ID="rptTechnologies" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Technology</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptVerticals" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Vertical</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptIndustries" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Industry</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptSolutions" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Solution</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<h3>Results</h3>
<asp:Repeater ID="rptMatchingSlides" runat="server" OnItemDataBound="rptMatchingSlides_ItemDataBound" OnItemCommand="rptMatchingSlides_Command">
<ItemTemplate>
<h4><asp:Literal ID="litName" runat="server"></asp:Literal></h4>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" />
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
<h3>Selected</h3>
<asp:Repeater ID="rptSelectedSlides" runat="server" OnItemDataBound="rptSelectedSlides_ItemDataBound">
<ItemTemplate>
<h4><asp:Literal ID="litName" runat="server"></asp:Literal></h4>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
Here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.BindData();
}
}
public List<string> SelectedSlides
{
get
{
if (Session["SelectedIDs"] != null)
{
string[] _ids = Session["SelectedIDs"].ToString().Split(new char[] { '|' });
List<String> _retVal = new List<string>();
foreach (string _id in _ids)
{
_retVal.Add(_id);
}
return _retVal;
}
else
{
return new List<string>();
}
}
set
{
//Set the session value
string _val = "";
foreach (string _id in value)
{
if (_val == "")
{
_val = _id;
}
else
{
_val += "|" + _id;
}
}
Session["SelectedIDs"] = _val;
}
}
protected void BindData()
{
//Filters
rptTechnologies.DataSource = Repository.GetTaxonomyItems();
rptTechnologies.DataBind();
rptVerticals.DataSource = Repository.GetTaxonomyItems();
rptVerticals.DataBind();
rptIndustries.DataSource = Repository.GetTaxonomyItems();
rptIndustries.DataBind();
rptSolutions.DataSource = Repository.GetTaxonomyItems();
rptSolutions.DataBind();
this.BindMatchingSlides();
}
protected void BindMatchingSlides()
{
...build list of ids from checkboxes...
rptMatchingSlides.DataSource = Repository.GetMatchingSlides(_selectedIDs);
rptMatchingSlides.DataBind();
}
protected void BindSelectedSlides()
{
if (this.SelectedSlides.Count > 0)
{
rptSelectedSlides.DataSource = this.SelectedSlides;
rptSelectedSlides.DataBind();
}
else
{
divSelectedSlides.Visible = false;
}
}
protected void rptMatchingSlides_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Literal _litName = (Literal)e.Item.FindControl("litName");
Button _btnSelect = (Button)e.Item.FindControl("btnSelect");
_litName.Text = ...set name here...
_btnSelect.CommandArgument = ...use unique ID of item from database...
_btnSelect.ID = "btnSelect_" + e.Item.ItemIndex;
}
}
protected void rptMatchingSlides_Command(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Select")
{
Item _slide = ...get data from database based on Command Argument...
if (_slide != null)
{
List<string> _selectedSlides = this.SelectedSlides;
_selectedSlides.Add(_slide.ID.ToString());
this.SelectedSlides = _selectedSlides;
}
this.BindSelectedSlides();
}
}
Thanks to Jeremy - removing the line of code where I was setting the ID fixed it. Doh! Somewhere else I had read that you needed to set a unique value for the IDs of the buttons in a repeater. So that must have been the culprit. Thanks to Jeremy.

dynamically hiding linkbuttons in a gridview

Here is my template field with 2linkbuttons in a gridview.
How do I hide one of the lnkbuttons depending on the user selection
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<table>
<tr>
<td align="center">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName= "Publish" CommandArgument="<%# Container.DataItemIndex %>"></asp:LinkButton>
</td>
<<td align="center">
<asp:LinkButton ID="LinkButton2" runat="server" CommandName= "Block" HeaderText="Block" CommandArgument="<%# Container.DataItemIndex %>">Block</asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(Status=="Posted")
{
LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
lbtn2.Visible = false;
}
if(Status=="Publish")
{
LinkButton lbtn1 = (LinkButton)e.Row.FindControl("LinkButton1");
lbtn1.Visible = false;
}
}
I am doing this using 2 linkbuttons in the template field.
Here if the Status == Posted, then hide LinkButton2.
If ItemType == Published, then hide LinkButton1.
I don't mind using only Linkbutton and set the commandName and commandArgument in aspx.cs`
I am getting an error at...
LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
lbtn2.Visible = false;
Error: Object reference not set to an instance pointing to lnbt2.Visible = false;
Any clues,
Thanks
Sun
Check to be sure that the row in question is a data row, not a header, etc. The issue is probably because the current row is a header or footer, so it doesn't contain your controls and throws an exception.
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
if(Status=="Posted")
{
LinkButton lbtn2 = (LinkButton)e.Row.FindControl("LinkButton2");
lbtn2.Visible = false;
}
if(Status=="Publish")
{
LinkButton lbtn1 = (LinkButton)e.Row.FindControl("LinkButton1");
lbtn1.Visible = false;
}
}
}
I know this is old but I was looking for the same thing; I was able to do it this way also and posting just for reference:
This is in a listview but should be same for gridview:
<asp:LinkButton ID="btnForms" runat="server" Text='MyButton' CommandName="MyCommandName"
Style='<%#GetHiddenTag(Eval("Status").ToString())%>' CommandArgument='<%#Eval("Status")%>' OnClick="MyOnClickCodeBehind" />
Codebehind:
public string GetHiddenTag(string Status)
{
if (Status.ToLower() == "completed")
return "visibility:hidden;";
return "visibility:visible;";
}

Asp.Net ListView's Items property is always empty

Good day
I have a user control that contains a ListView which is being used to display tabs.
I am databinding the ListView and on the OnItemDataBound event adding the tab elements.
However the Items property never contains anything and is always empty (on PostBack and on ItemDataBound).
Markup:
<asp:ListView ID="SaleTabsListView" runat="server" OnItemDataBound="SaleTabsListView_OnItemDataBound" ItemPlaceholderID="SaleTabsPlaceHolder" EnableViewState="true">
<LayoutTemplate>
<div class="tabs">
<asp:PlaceHolder runat="server" ID="SaleTabsPlaceHolder" />
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="ItemPlaceHolder" />
</ItemTemplate>
</asp:ListView>
Code behind:
protected void SaleTabsListView_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var saleTab = ((ListViewDataItem)e.Item).DataItem as SalesTab;
if (saleTab != null)
{
var placeHolder = e.Item.FindControl("ItemPlaceHolder") as PlaceHolder;
var htmlAnchor = new HtmlAnchor();
htmlAnchor.Attributes.Add("id", saleTab.Id);
htmlAnchor.Attributes.Add("class", saleTab.IsCurrent ? currentTabClass : string.Empty);
var emptyLabel = new Label();
var label = new Label {Text = saleTab.Title};
label.Attributes.Add("id", saleTab.Id + "Label");
label.Attributes.Add("class", saleTab.IsComplete ? completeClass : incompleteClass);
emptyLabel.Controls.Add(label);
htmlAnchor.Controls.Add(emptyLabel);
placeHolder.Controls.Add(htmlAnchor);
}
}
}
So my question is: is the binding I'm doing somehow screwing with the Items property?
Thanks

Setting the Selectedindex/selectedvalue of a Dropdownlist in a repeater not working

I have a repeater with a DropDownList in it. I set the datasource of this list in the itembound event en set the selectedindex. When I debug the selectedindex is set, but when the page is done loading for all the item the default item is selected.
This is my code:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var ddl = (DropDownList)e.Item.FindControl("DataFeedItems");
ddl.DataSource = FilterDropDownData();
ddl.DataTextField = "ColumnName";
ddl.DataValueField = "ColumnName";
ddl.DataBind();
ddl.SelectedValue = "Select";
ddl.SelectedIndex = 28;
}
protected DataTable FilterDropDownData()
{
var importedFeedColums = I make the table here;
DataRow newRow = importedFeedColums.NewRow();
newRow[0] = "Selecteren";
importedFeedColums.Rows.Add(newRow);
return importedFeedColums;
}
I Als tried to using the Databound even of the dropdown list, but this didnt work either:
protected void DataFeedItems_DataBound(object sender, System.EventArgs e)
{
var ddl = (DropDownList) (sender);
ddl.SelectedValue = "Selecteren";
ddl.Items[28].Selected = true;
}
<asp:Repeater ID="Repeater1" runat="server"
onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<li>
<label><%# DataBinder.Eval(Container.DataItem, "ColumnName") %></label>
<asp:DropDownList ID="DataFeedItems" ClientIDMode="Static" runat="server" DataSource='<%# FilterDropDownData() %>'
DataTextField="ColumnName" DataValueField="ColumnName" OnDataBound="DataFeedItems_DataBound" >
</asp:DropDownList>
<input id="Hidden1" runat="server" clientidmode="Static" type="hidden" value='<%# DataBinder.Eval(Container.DataItem, "ColumnName") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
When I post the form I can get the selectedvalue and text of each DropDownList. What am I doing wrong
What does FilterDropDownData() return?
Have you tried this?
ddl.Items.FindByValue("Selecteren").Selected = true;
or
ddl.Items.FindByText("Selecteren").Selected = true;
This approach will fail since a drop-down can not have multiple items selected. And setting the "Selected = true" will do exactly the same.
Only way you can set an item as selected is by using the SelectedIndex property of DropDownList.
Ex:ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("Selecteren"));

Resources