DropDownList inside Grid - asp.net

I am using ASP.NET, I have a dropdownlist inside of a grid (radGrid).
What I like to happen is that when the dropdownlist appears, I like it to default to
"Please Select" only if the field that it is binding to is blank. Else, I like to to get the value from the DataSource.
I have the following code:
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
For the DataSource here is the code:
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
Here is the code in the code-behind:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
When it does the Binding, if the value is blank, I get an error saying that it could not find the value.

try:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list.Items.Count.equals(0))
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}

Use Grid PreRender event for this. May you would need to assign the value to some hidden label and access it inside prerender method and assign it to the dropdown.
<ItemTemplate>
<asp:Label runat="server" ID="lblValue" Text='<%# Eval("YourValue")%>' Visible="false" />
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
</ItemTemplate>
On code behind:
protected void GridView1_PreRender(object sender, EventArgs e)
{
for(int i=0;i<Gridview1.Rows.Count;i++)
{
Label lblValue = (Label)Gridview1.Row[i].FindControl('lblValue');
DropdownList ddl = (DropdownList) Gridview1.Row[i].FindControl('ddlEroGroup');
ddl.Items.Insert(0, new ListItem("Please Select", ""));
if(lblValue!=null && !String.IsNullOrEmpty(lblValue.Text))
ddl.SelectedValue = lblValue.Text;
}
}

Related

Trigger SelectedIndexChanged event ASP.NET

I have a DropDownList inside a GridView. I want to make some updates on database inside the SelectedIndexChanged it's not being triggered.
PS: I tried all the solutions I found over internet but always the same problem.
Here is code:
<asp:TemplateField HeaderText="Accepté" ControlStyle-Width="90px">
<ItemTemplate >
<asp:Label ID="lblState" runat="server" Text='<%# Eval("StateCode") %>' Visible = "False" />
<asp:DropDownList ID="ddlState" runat="server" Visible = "False" OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField >
And the code behind
protected void grwConsent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text != " ")
{
DropDownList ddlState = e.Row.FindControl("ddlState") as DropDownList;
if (null != ddlState)
{
ddlState.Visible = true;
string stateValue = (e.Row.FindControl("lblState") as Label).Text;
ConsentHelper.LoadConsentStatesInList(ddlState,"-----",stateValue);
ddlState.Items.RemoveAt(0);
ddlState.Items.FindByText(stateValue).Selected = true;
}
}
}
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
//Database Updates
}
Thank you!
Try adding these properties to you DropDownList:
ViewStateMode="Enabled"
EnableViewState="true"
AutoPostBack="true"
<asp:DropDownList ID="ddlState" AutoPostBack="true" EnableViewState="true"
ViewStateMode="Enabled" runat="server" ...

Dropdownlists with parent-child relation in EditItemTemplate Gridview not working

I have a page with gridview in it.
My gridview shows the products Information and Admin can Edit gridviews columns.
Two of my columns show the brand name and category name for each product;
I use lables in ItemTemplate tag in my grid view to show these two columns value and I use two dropdownlists(branddrop,categorydrop)
in my EditItemTemplate tag for editing these two columns value,when admin select an item in branddrop the categorydrop should show categories name which are related to selected brand name in branddrop.
Brands name in my brand table in database are:
Samsung, Nokia,Sony Ericsson,Apple,LG,HTC....
and my categories name in category table are :
Galaxy Nexus,Galaxy Tab 2 7. 0,Galaxy S3,Asha,Lumia,iPhone,iPad,Xperia Arc,Xperia Neo,Xperia X8,Cookie 3g,Cookie lite,Km555e,Optimus l9,Optimus elite,Optimus g,wt18i,w8,500,n8...
When I click the Edit button, first item in the branddrop is Equal to brandlable.
Text in ItemTemplate and it works fine my problem is the first item in category drop is not Equal to categorylable.text in ItemTemplate and the category drop does not show the related categories name to brandname.for every product it shows iphone and ipad so I have to select another items in branddrop and then select again the related brandname which is related to that product then the categorydrop can show the list of related categories name.I tried to use brandDrop_SelectedIndexChanged and GridView1_RowEditing but it is not work. I dont know how to solve it.
this is my first code:
<asp:TemplateField HeaderText="brand name">
<ItemTemplate>
<asp:Label ID="brandname" runat="server" Text='<%#Eval("brand_name") %>'></asp:Label>
<asp:Label ID="idfrombrand" runat="server" Text='<%#Eval("idfrombrands") %>' Visible="false"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="br" runat="server" Text='<%# Eval("idfrombrands") %>' Visible="false"></asp:Label><%--OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" --%>
<asp:DropDownList ID="brandDrop" runat="server" DataTextField="brand_name" DataValueField="id" DataSourceID="SqlDataSource4" AutoPostBack="true" OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [id],[brand_name] from [brands]" ></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="category name">
<ItemTemplate>
<asp:Label ID="catname" runat="server" Text='<%# Eval("category_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="OldCatName" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="categoryDrop" runat="server" AutoPostBack="true" DataTextField="category_name" DataValueField="id" DataSourceID="SqlDataSource3"> <%-- --%>
</asp:DropDownList>
<asp:Label ID="cat" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false" ></asp:Label>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [category_name],[id],[idfrombrands] from [categories] where idfrombrands=#idfrombrands " >
<SelectParameters>
<asp:ControlParameter ControlID="brandDrop"
Name="idfrombrands" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
this is my code behind for GridView1_RowDataBound and GridView1_RowUpdating:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int brand=0;
int category=0;
//Drop Brand--------------------------------------
DropDownList list1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("brandDrop");
Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("br");
if (list1.SelectedItem.Value != null)
{
brand = Convert.ToInt32(list1.SelectedItem.Value);//NewIdFromBrand
}
else
{
brand = Convert.ToInt32(lbl.Text);
}
//Drop Category----------------------------------------
DropDownList list2 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("categoryDrop");
Label lbl2 = (Label)GridView1.Rows[e.RowIndex].FindControl("OldCatName");
//int NewIdFromBrand2 = -1;
if (list2.SelectedItem.Value != null)
{
category = Convert.ToInt32(list2.SelectedItem.Value);//NewIdFromBrand2
}
else
{
category = Convert.ToInt32(lbl2.Text);
}
//Photo-------------------------------------------
string photoname = System.Guid.NewGuid().ToString();
GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fileUpload = row.FindControl("FileUploadimg") as FileUpload;
Label lbl3 = (Label)GridView1.Rows[e.RowIndex].FindControl("oldImage");
if (fileUpload != null && fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/P_Image") + photoname + fileUpload.FileName);
SqlDataSource1.UpdateParameters["path"].DefaultValue = "~/P_Image" + photoname + fileUpload.FileName;
}
else
{
SqlDataSource1.UpdateParameters["path"].DefaultValue = lbl3.Text;//oldImage.Text;
}
int prid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
DataTable tb = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateProduct";
cmd.Parameters.AddWithValue("#brandid", brand );
cmd.Parameters.AddWithValue("#catid", category );
cmd.Parameters.AddWithValue("#pid", prid);
try
{
cn.Open();
cmd.ExecuteNonQuery();
SqlDataSource1.DataBind();
}
catch (Exception ex2)
{
}
finally { cn.Close(); }
//GridView1.EditIndex = -1;
//GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
//Label1.Text = ddlStatus.SelectedValue;
}
}
}
}
}
Thank you so much Abide Masaraure.you helped me a lot.
I deleted grideview_rowediting and braddrop_selectedIndexChange event And just added two lines to my GridView1_RowDataBound event.
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
now my event is like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
}
}
}
}
}
Eureka!!!.You owe me a cup of coffee.I replicated your problem and realized after two hours that you need to actually hook to your index selected changed event.The trick is to use the naming container property to locate your drop downs,they think are pretty hidden ,but the sender argument enables us to expose them when dropband dropdown fires. And presto everything works like a charm.
Use this code snipet in your selected changed event.
protected void dropBand_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList dropBand = (DropDownList)sender;
SqlDataSource dsc = (SqlDataSource)dropBand.NamingContainer.FindControl("SqlDataSource3");
DropDownList categoryDrop = (DropDownList)dropBand.NamingContainer.FindControl("categoryDrop");
dsc.SelectParameters("BrandID").DefaultValue = dropBand.SelectedValue;
categoryDrop.DataBind();
}
I can send you a zip file of the demo this time if you happen to continue having issue.Happy Coding!!!.
I need to see your code you are using in your selected index changed event.
The following cascading drop down technique will take away all the suffering you have in trying to hook up the parent and its children...I use this wonderful feature in the Ajax control toolkit in all my projects.You can use any data retrieval method you want as long it returns an array.I am using linq in this example for data retrieval.
Assuming I have tables named Brand and Model and classes : Brand and Model and collections: Brands and Models
In 'YourWebServicePath.asmx' (Web service file)
<WebMethod()> _
Public Function GetBrands(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim result = From b As Bands In Brand.Brands Select New CascadingDropDownNameValue(b.BrandDesc, b.BrandID.ToString())
Return result.ToArray()
End Function
<WebMethod()> _
Public Function GetModels(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim brandID As Guid
Dim brandValues As StringDictionary = AjaxControlToolkit.CascadingDropDown._
ParseKnownCategoryValuesString(knownCategoryValues)
brandID = New Guid(brandValues("Brand"))
Dim result = From m As Models In Model.GetModels() Where m.brandID = brandID Select New CascadingDropDownNameValue(m.ModelDesc,
_ m.ModelID.ToString())
Return result.ToArray()
End Function
MarkUp
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<EditItemTemplate>
<asp:DropDownList ID="dropBrand" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="BrandCascadingDropDown"
runat="server"
Category="Brand"
TargetControlID="dropBrand"
PromptText="-Select Brand-"
LoadingText="Loading Brands.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetBrands">
</cc1:CascadingDropDown>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="dropModel" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="ModelCascadingDropDown"
runat="server"
Category="Model"
TargetControlID="dropModel"
ParentControlID="dropBrand"
PromptText="-Select Model-"
LoadingText="Loading Models.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetModels" >
</cc1:CascadingDropDown>
And thats all you need.No need of wiring the events.And voila! let the toolkit perform the magic.
To use the above code i gave you in a row editing event you have to modify it like so.Then those objects won't be null.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView testgrid = (GridView)(sender);
testgrid.EditIndex = e.NewEditIndex;
testgrid.DataBind();
DropDownList dropBand = (DropDownList)testgrid.Rows[e.NewEditIndex].FindControl("ddlProducts");
//
}
Something is definitely happening in your page cycle and is keeping on biting you.I suggest zip an mdf of your database and the offending aspx page and let me tackle it from here if you don't get it to work.Never give up.

Dropdown list loses value on gridview RowCommand

I have a DropDownList in a GridView. I am filling the GridView dynamically in GridView RowCreated(). I want to get that DropDownList's value when I click the GridView's Command Button.
In the RowCommand function, I am trying to get the value. However, I can't find the control in that function. Surprisingly, another DropDownList works fine in the same function.
C# code follows:
if (Request.Params["ID"] != null && Request.Params["ID"] != "")
{
FirmID = Convert.ToInt32(Request.Params["ID"]);
//OfficeList = IFARecord.GetOffices(FirmID);
}
if (!IsPostBack)
{
GV_SABAdvisers.DataSourceID = "objectDataSourceSAV";
GV_SABAdvisers.DataBind();
}
protected void GV_SABAdvisers_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Index")
{
int Index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GV_SABAdvisers.Rows[Index];
//Not working
DropDownList Offices = row.FindControl("ddlLocation") as DropDownList;
String officeID = (Offices is DropDownList) ? Offices.SelectedValue : null;
DropDownList ddlJobTitle = row.FindControl("ddlJobTitle") as DropDownList;
if (ddlJobTitle is DropDownList)
{
newAdviserJobTitle.JobTitleID = Convert.ToInt32(ddlJobTitle.SelectedValue);// this works fine.
}
}
}
protected void GV_SABAdvisers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlLocation = e.Row.FindControl("ddlLocation") as DropDownList;
DropDownList ddlJobTitle = e.Row.FindControl("ddlJobTitle") as DropDownList;
DataTable OfficeList = GetOffices(FirmID);
DataTable dtJob = MyTouchstone.Advisers.AdviserFirmJobTitle.AllJobTitle();
foreach (DataRow aOffice in OfficeList.Rows)
{
ddlLocation.Items.Add(new ListItem(aOffice["Address1"].ToString() + ", " + aOffice["Postcode"].ToString(), aOffice["OfficeID"].ToString()));
}
foreach (DataRow aJob in dtJob.Rows)
{
ddlJobTitle.Items.Add(new ListItem(aJob["JobTitle"].ToString(), aJob["JobTitleID"].ToString()));
}
}
}
ASP markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:GridView ID="GV_SABAdvisers" AutoGenerateColumns="false" PageSize = "10"
CssClass="cssPager" AllowPaging="true" AllowSorting="true"
OnPageIndexChanging="GV_SABAdvisers_PageIndexChanging"
runat="server" onrowcommand="GV_SABAdvisers_RowCommand"
onrowcreated="GV_SABAdvisers_RowCreated">
<PagerStyle />
<Columns>
<asp:TemplateField HeaderText="Job Title">
<ItemStyle Width="80px" />
<ItemTemplate>
<asp:DropDownList ID="ddlJobTitle" Width="80px" runat="Server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemStyle Width="200px" />
<ItemTemplate>
<asp:DropDownList ID="ddlLocation" Width="80px" runat="Server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Can anyone help me, please?
I don't see where have you used the CommandName "Index" in your source code.

Required field validater in repeater

I have a repeater control and textbox in that repeater. I want a required field validator in the textbox ho can i do this
<asp:Repeater id="myRep" OnItemDataBound="rep_ItemDataBound" runat="server">
<ItemTemplate>
<asp:TextBox id="tx" runat="server" />
<asp:RequiredFieldValidator id="myVal" ControlToValidate="tx" ErrorMessage="Required" runat="server" />
</ItemTemplate>
</asp:Repeater>
UPDATE
Add this to code-behind (also modify the markup a bit to subscribe to an event, see above):
protected void rep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RequiredFieldValidator val = (RequiredFieldValidator)e.Item.FindControl("myVal");
TextBox tb = (TextBox)e.Item.FindControl("tx");
val.ControlToValidate = tb.ID;
}
If you want all textboxes in a repeater to be validated by a single button click then thats simple like this
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:TextBox ID="txt" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator ID="rqf" ControlToValidate="txt"
ErrorMessage="*" ValidationGroup = "TestValidationGroup" runat = "server">
</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID = "btnSubmit" runat = "server" ValidationGroup = "TestValidationGroup" />
No need to check for any event for databound or anything.
You can set ControlToValidate value on repeater itemdatabound.
Try this one
<asp:Repeater ID="rptSample" runat="server">
<ItemTemplate>
Name:<br />
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" ControlToValidate="txtName" runat="server" Display="Static" ErrorMessage="Name field cannot be left blank"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
protected void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
((RequiredFieldValidator)e.Item.FindControl("myVal")).ValidationGroup = ((TextBox)e.Item.FindControl("tx")).UniqueID;
}
}
protected void Repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
tblData tbldata = e.Item.DataItem as tblData;
RequiredFieldValidator val = (RequiredFieldValidator)e.Item.FindControl("rfv");
if (tbldata.FieldName.ToUpper().Contains("NOT NULL")) {
TextBox tb = (TextBox)e.Item.FindControl("txtDATFieldName");
val.ControlToValidate = tb.ID;
}
else {
val.Enabled = false; // disable when you dont need a validator
}
}
Maybe you want have a validation per row... Set the validation group to a group per row like this
ValidationGroup='<%# "gropname" + Eval("Id") %>'
do this in the validator, textbox and the button
HTH
G.
I kept getting a duplicate key exception in RegisterExpandoAttribute trying to do this.
I was using a UserControl inside a repeater, when "OnDataBinding" instead of "ItemDataBinding"
This worked for me:
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.DataBinding" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
foreach (Control ct in this.Controls)
{
BaseValidator bv = ct as BaseValidator;
if (null == bv)
{
continue;
}
bv.ControlToValidate = this.FindControl(bv.ControlToValidate).ID;
bv.ValidationGroup = this.ValidationGroup;
}
}
And yes, I don't think it makes any sense either

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