can't change selection after DDL get deafult value - asp.net

am having a data based dropdownlist which the default selection is set by user session. it is working fine, but if i try to select a different item on the list after, its jump back to the default. am using visual studio 2015, web form, asp.net
i try selecting default item in 2 way and still the same problem
if (Session["plyer2"] != null) {
string DropDownListSelected = Session["plyer1"].ToString();
DropDownList1.ClearSelection();
DropDownList1.Items.FindByValue(DropDownListSelected).Selected = true;
DropDownList2.SelectedValue = Session["plyer2"].ToString(); }
have been searching google for the last 2 day didn't find help
the DDL is autopostback
the code is in the .aspx.cs file: protected void Page_Load(object sender, EventArgs e)
the databind is in the .aspx file
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource5" DataTextField="forshow" DataValueField="forshow" AppendDataBoundItems="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="1">בחר גארד</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [forshow] FROM [players] WHERE ([position] = #position)">
<SelectParameters>
<asp:QueryStringParameter DefaultValue="גארד" Name="position" QueryStringField="גארד" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

well its no a real answer to the problem, but since I'm using session to select item, i add
Session.Abandon();
so its cancelling the IF statement next page load and that's good enough for me

Related

can't get checked nodes from RadTreeView in code behind

I have a rad tree view as below:
<telerik:RadTreeView ID="rtreevwParvandehShakhsi" runat="server" CheckBoxes="true" TriStateCheckBoxes="False" DataSourceID="SqlDataSource1" EnableViewState="true"></telerik:RadTreeView>
<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:PigisConnectionString %>' SelectCommand="SELECT SCT_ParvandehShakhsi.*, ParvandehShakhsi_ID AS Expr1, ParvandehShakhsi_Code AS Expr2, ParvandehShakhsi_Desc AS Expr3, ParvandehShakhsi_ParentID AS Expr4, ParvandehShakhsi_Personel_ID AS Expr5 FROM SCT_ParvandehShakhsi WHERE (ParvandehShakhsi_Personel_ID = #personel_ID)">
<SelectParameters>
<asp:SessionParameter SessionField="user_personel_id" Name="personel_ID"></asp:SessionParameter>
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="btnSubmitParvandehShakhsi" runat="server" Text="ثبت" OnClick="btnSubmitParvandehShakhsi_Click" CausesValidation="false" Font-Size="Medium" CssClass="btn green" Height="38px" Width="63px" />
and I want to get the checked nodes in code behind. i use below code but it dont get the checked node for me! where is the problem?
protected void btnSubmitParvandehShakhsi_Click(object sender, EventArgs e)
{
foreach (RadTreeNode tnode in rtreevwParvandehShakhsi.CheckedNodes)
{
RadWindowManager1.RadAlert("node value : " + tnode.Value, 330, 180, "پیام سیستم", null, null);
}
}
Try setting the DataSourceId of the treeview manually on Page_Load if it is not PostBack.
I think the treeview's datasource gets overriden on page load before the the button click event fires leading to CheckedNodes being empty.

How to set a asp:DropDownList SelectedValue to a Session Variable?

There are several articles describing how to do this is code behind however:
Is it possible to set the value of a dropdownlist to a session variable on the aspx page?
I am using SqlDataSource to populate the dropdownlist so do not wish to add code behind if it can be avoided.
<asp:DropDownList ID="ddl" runat="Server" DataSourceID="sqlDS" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server" SelectCommand="spDS" SelectCommandType="StoredProcedure" />
Set Session("ID") as selected value on load?
The dropdown list is already populated from the sqldatasource. I just want to set the initial value on page load.
You need a server side code in order to use Session. The following code doesn't requires code behind file, but again the code inside script will run at server side.
<asp:DropDownList ID="ddl" runat="Server"
DataSourceID="sqlDS"
DataValueField="ID"
DataTextField="TEXT"
AppendDataBoundItems="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server"
SelectCommand="spDS" SelectCommandType="StoredProcedure" />
<script runat="server">
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SelecteValue"] = ddl.SelectedValue;
}
</script>
Note: Make sure AutoPostBack="True" for DropDownList.
Do not mix code with markup. It makes sense to separate them for many reasons. So ASPX will have just the presentation, and CS/VB just the code logic.
When you compile/deploy your side to production - there will not be "the second page" - only ASPX page will remain. Code will be compiled into a DLL.
you'll need an event for your dropdown list on change. Are you using C# or VB.net for your codebehind?
add to onSelectedIndexChanged="ddl_OnSelectedIndexChanged"
to your code behind add:
{this is C# vb is similar}
protected void ddl_OnSelectedIndexChanged(Object sender, EventArgs e)
{
Session["selectedID"] = ddl.selectedValue;
}
to your page load, add
if (isPostback)
{
ddl.selectedValue = Session["selectedID"];
}

PostBack DataBind error: "Ensure that the control is added to the page before calling DataBind."

I have a program that allows the user to use a few dropdowns to pick a topic and attribute, then the data are pulled that match on both of those conditions. In the gridview are a lot of templatefields use textboxes for instant editing (a submit button saves all changes) as well as a template with a dropdown bound to a parameter. This was all working hunky-dory for quite a while.
Then, we changed some of the data in the tables (keeping all the same field names) and now the page loads perfectly fine on launch but then as soon as you select something different in any of the drilldown dropdowns the page fails. I get an error saying
"The DropDownList control 'TagDDL' does not have a naming container.
Ensure that the control is added to the page before calling DataBind."
(TagDDL is the dropdown in the templatefield in gridview). If I simply remove this templatefield, I get a similar (though different) error on a hyperlinkfield, removing this gives me an error in a boundfield, so obviously it's not tied to any one thing.
My idea is that it has something to do with how databinding works on post-back, since the page loads perfectly initially, the dropdowns have 'Enable PostBack' and the error messages refer to DataBind. Any ideas?
The SqlDataSource that builds Gridview (leaving out the drilldown dropdowns for now)
<asp:SqlDataSource ID="MasterTable" runat="server"
ConnectionString="<%$ ConnectionStrings:spvConnectionString %>"
SelectCommand="exec pmtv2.maintable_display 1, #IPG_Assigned, #CompetitorName, #enterprise_zone, #Banner, #BrandName"
<SelectParameters>
<asp:ControlParameter ControlID="ChooseBanner" Name="Banner" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ChooseIPGs" Name="IPG_Assigned" PropertyName="SelectedValue" Type="Int32" />
<asp:ControlParameter ControlID="ChooseBrands" Name="BrandName" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ChooseComps" Name="CompetitorName" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="ChooseZone" Name="enterprise_zone" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
<div id="MasterDiv" style="width:90%">
<asp:GridView ID="MasterDisplay" runat="server"
AllowSorting="True" AutoGenerateColumns="False"
DataKeyNames="productKey,banner,enterprise_zone,userID" DataSourceID="MasterTable"
OnRowDataBound="MasterDisplay_RowDataBound"
OnSorting="MasterDisplay_Sorting"
class="mGrid" AlternatingRowStyle-CssClass="mGridAlt">
</AlternatingRowStyle>
<Columns>
<asp:TemplateField HeaderText="Description" SortExpression="productdescriptionlong">
<ItemTemplate>
<a href="javascript:openPopup('JustinPractice4.aspx?UPC=<%# Eval("UPC") %>
&banner=<%# Eval("banner") %>&enterprise_zone=<%# Eval("enterprise_zone") %>')"><%# Eval("productdescriptionlong")%></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="BrandName" HeaderText="Brand"
SortExpression="BrandName" />
<asp:TemplateField HeaderText="New Price" SortExpression="new_base_retail">
<ItemTemplate>
<asp:TextBox ID="RWNextPrice" runat="server"
Text='<%# Bind("new_base_retail", "{0:N2}") %>' Width="60px"
class="calculate" onchange="lineItemRipple(this)"
Visible='<%# ShowBox %>'></asp:TextBox>
<asp:Label ID="RNextPrice" runat="server" Text='<%# Eval("new_base_retail", "{0:c}") %>'
Visible='<%# ShowLabel %>'></asp:Label>
<asp:HiddenField ID="lineCode" runat="server" Value='<%# Eval("line_code") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField DataImageURLField="unique_flags" HeaderText="Flags"
DataImageURLFormatString="Media/Images/{0}.png" SortExpression="unique_flags"/>
<asp:TemplateField HeaderText="Tag Type" SortExpression="tag_type">
<ItemTemplate>
<asp:DropDownList ID="TagDDL" runat="server"
DataSourceID="dimTags"
DataTextField="Tag_type_name"
DataValueField="Tag_type_name"
SelectedValue='<%#Bind("tag_type") %>'
visible='<%#ShowBox %>'>
</asp:DropDownList>
<asp:Label ID="TagR" runat="server"
Text='<%# Eval("tag_type") %>'
Visible='<%# ShowLabel %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Commit" runat="server" Text="Commit Changes" OnClick="Commit_Click"
class="button"/>
and the relevant code behind:
protected void Page_Load(object sender, EventArgs e) {
ErrorMsg.Text = "test45";
}
protected void MasterDisplay_RowDataBound(object sender, GridViewRowEventArgs e) {
DataSourceSelectArguments sr = new DataSourceSelectArguments();
DataView dv = (DataView)CheckForCommit.Select(sr);
if (dv.Count != 0) {
CommittedOrNot.Text = dv[0][0].ToString();
}
//pulling results from a SqlDataSource confirming presence of data
//calculations to maintain a running tally of certain fields for later use
}
protected void Commit_Click(Object sender, EventArgs e) {
string tagValue = "FLAG";
foreach (GridViewRow gvr in MasterDisplay.Rows) {
tagValue = ((DropDownList)gvr.FindControl("TagDDL")).SelectedValue;
MasterDisplay.UpdateRow(gvr.RowIndex, false);
} //for every row, update it
MasterDisplay.DataBind();
}
It was a simple error of trying to add to a DDL before I had actually pulled the data needed to bind it. Changing the order of things slightly did the trick
I am glad you found your answer. I had a similar issue on a UserControl (ascx) that was being loaded a run-time. I, too, had made a change to my data source and the corresponding sql data sources. (In my case, I was replacing the sql data sources with an entity model.)
What I found was that one of my controls would bind to the new data source (via the code behind) with no problems. The code looked as follows:
gridSomeData.DataSource = controller.GetListOfAssociatedParts();
gridSomeData.DataBind();
However, in the same method, the next section of code would fail when the DataBind() method was called. The code looked as follows:
drpDataList.DataSource = controller.GetListOfParts();
drpDataList.DataTextField = "PartID"
drpDataList.DataValueField = "PartKey"
drpDataList.DataBind();
It turned out, that when I removed the prior ASCX markup for the SqlDataSource objects, I failed to remove the reference in the DataSourceID attribute of the drop down control. So when I called the DataBind() method, the binding engine checked the attributes of the control, found a name DataSourceID, and immediately went looking for it in the control hierarchy of the UserControl. When the binding engine failed to find the object, it threw the exception "The DropDownList control [...] does not have a naming container..."
I will admit that this particular exception is somewhat misleading, as it is really the binder being confused over which instructions to follow for the data source (the code behind, or the markup in the ascx file).
I hope this helps with some perspective. :)

Duplicate items in dropdownlist!

Ok I really hope you guys can help me with this, I've spent the past 2 days trying to figure it out and I think I'm about to throw my computer out the window, so I thought I might as well ask here first:
I'm designing a web page with two dropdownlists, one for the Make of a car, the other for the Model, both bound to a database with separate SQLDataSources, and using a distinct statement. I add "All" at the top of both by setting appendDataBoundItems = true and adding items named all. Then when I fill the Make with a querystring all the model items get added twice (but only the databound items).
Here's my code:
<asp:DropDownList ID="DropDownMake" runat="server"
DataSourceID="SqlMakes" DataTextField="Make" DataValueField="Make"
AppendDataBoundItems="True" EnableViewState="False" AutoPostBack="True">
<asp:ListItem Selected="True" Value="All">All</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownModel" runat="server"
AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlModels"
DataTextField="Model" DataValueField="Model" EnableViewState="False">
<asp:ListItem>All</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlMakes" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Make] FROM [Parts]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlModels" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Model] FROM [Parts] WHERE ([Make] = #Make)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownMake" Name="Make"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
'And in the VB file:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
DropDownMake.SelectedValue = Request.QueryString("Make")
DropDownModel.SelectedValue = Request.QueryString("Model")
End Sub
If I remove the line "DropDownMake.SelectedValue = Request.QueryString("Make")" it doesnt produce duplicates anymore. What is going on?? I swear I've spent more time developing entire iphone apps, if anyone helps figure this out I think I'm going to have to make an award for you.
Thank you!!
I think your databind method might be fired twice. Have you tried to set appendDataBoundItems=false and then attach an event handler for the OnDataBound event and insert your top item in the event handler instead?
protected void yourDdlControl_DataBound(object sender, EventArgs e)
{
if (yourDdlControl.Items.Count > 0)
{
yourDdlControl.Items.Insert(0, "All");
yourDdlControl.Items[0].Value = "";
yourDdlControl.SelectedIndex = 0;
}
}
}
Ok, so that is c# code, but you should be able to translate it :). Also, you can set the selected value in the DataBound instead based on the existence of your query parameters.
Put your code inside not postback i.e.
If Not Page.IsPostBack Then
DropDownMake.SelectedValue = Request.QueryString("Make")
DropDownModel.SelectedValue = Request.QueryString("Model")
End If

asp.net dropdownlist

I have two dropdownlists for a search, the 1st list is for the city and the second is for the area within the selected city. I would like to add a default value in the 2nd dropdownlist that will search ALL of the areas by default unless a specific area is selected from the list that contains the areaID for a specific search.
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="cityName" AutoPostBack="true" DataValueField="cityID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Cities]"></asp:SqlDataSource>
<asp:DropDownList ID="DropArea" runat="server" DataSourceID="SqlArea"
DataTextField="areaName" DataValueField="areaID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlArea" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [area] WHERE ([cityID] = #cityID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="0" Name="cityID"
PropertyName="SelectedValue" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Search" onclick="Button1_Click" />
Bind the second from code behind. Create a data table and insert the Select text at the begining and bind the datatable to the DDL.
DataTable dt =
DataRow dr = dt.NewRow()
dr["areaName"] = "All";
dr["SqlArea"] = "All";
tbldata.Rows.InsertAt(dr,0);
DropArea.DataSource = dt;
DropArea.DataBind();
You can try to add for second dropdownlist OnDataBound="DropArea_DataBound" event.
And use in code:
protected void DropArea_DataBound(object sender, EventArgs e)
{
DropArea.Items.Insert(0, new ListItem() {Value = "-1", Text = "ALL"});
}
And then when you handle click event, check:
var value = DropArea.SelectedItem.Value;
if(string.equals(value, '-1')
{
use your logic here
}
Hope it will help with your problem.
Best regards, Dima.
Chris,
I got the idea below from an answer HERE, but basically you want to modify your query to be in the form of the following:
Your Original:
SELECT * FROM [Cities]
Change To:
SELECT City FROM [Cities]
UNION ALL
SELECT 'ALL'
Old question, but you never found an answer.

Resources