can't get checked nodes from RadTreeView in code behind - asp.net

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.

Related

can't change selection after DDL get deafult value

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

DevExpress TreeList settingSelection recursive

ASPX
<dx:ASPxTreeList ID="ASPxTreeListLocations" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSourceUserMetersTree" KeyFieldName="sno" ParentFieldName="ParentId"
Width="300px" SettingsSelection-Recursive="true" Theme="Office2010Black">
<Columns>
<dx:TreeListTextColumn FieldName="Text" VisibleIndex="0" Caption="Lokasyon">
</dx:TreeListTextColumn>
</Columns>
<SettingsBehavior AutoExpandAllNodes="True" />
<SettingsSelection Enabled="True" />
</dx:ASPxTreeList>
<asp:SqlDataSource ID="SqlDataSourceUserMetersTree" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>">
</asp:SqlDataSource>
CODEBEHID
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSourceUserMetersTree.SelectCommand = "SELECT * FROM Tree";
ASPxTreeListLocations.DataBind();
}
QUESTION:
Codes are working well. I want to recursive selection, but this property is not working. If I define SqlDataSource selectCommand in aspx side, it works. I cant find any solution. No error message. Any advice?
Thanks...
Try to add the option recursive = "true" to your tree settings,
NP

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. :)

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.

In a FormView, how to change the property of a Label in the ItemTemplate?

In ASP.NET, I have a FormView which is bound to an ObjectDataSource. The FormView has an ItemTemplate with a Delete button, and a Label. I'm handling the OnItemDeleted event of the FormView to detect if my business class throws an exception upon deletion. If an exception is detected, I change the text of the Label to whatever the exception message is.
Well, it's just not working.
I detect the Exception fine, but the Text of the Label never gets changed. When the page reloads, the default text stays. I have also tried to rebind the FormView with DataBind() after assigning the new Text, but it's not working either.
In a desperate attempt at tracking the problem, I've taken the Label out of the FormView and it's working fine.
What I am doing wrong?
ASPX page:
<asp:ObjectDataSource ID="MyObjectDataSource"
TypeName="MyScopeRepository"
SelectMethod="GetById"
DeleteMethod="Delete"
runat="server">
<SelectParameters>
<%-- The id param here is from a DropDownList, not included in the example for clarity. --%>
<asp:ControlParameter Name="id" Type="Int32" ControlID="MyDropDownList" PropertyName="SelectedValue" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
</asp:ObjectDataSource>
<asp:FormView ID="MyFormView" DataSourceID="MyObjectDataSource"
RenderOuterTable="false"
DataKeyNames="Id"
OnItemDeleted="MyFormViewItemDeleted"
runat="server">
<ItemTemplate>
<asp:Button CssClass="Button Small" Text="Delete" CommandName="Delete" runat="server" /><br />
<asp:Label ID="ErrorLabel" Text="Default text" runat="server" />
</ItemTemplate>
</asp:FormView>
Code-behind:
protected void MyFormViewItemDeleted(object sender, FormViewDeletedEventArgs e)
{
if (e.Exception != null && e.Exception.InnerException is RepositoryException)
{
Label errorLabel = (Label)MyFormView.FindControl("ErrorLabel");
errorLabel.Text = e.Exception.InnerException.Message;
e.ExceptionHandled = true;
// I also tried this to no avail.
//MyFormView.DataBind();
}
}
Thanks a lot!
EDIT: I've checked all events fired by the FormView when clicking the Delete button and here is what I got:
OnInit
OnItemCreated
OnLoad
OnItemCommand
OnItemDeleting
OnItemDeleted
OnItemCreated
OnDataBound
OnPreRender
OnUnload
So we can see that OnItemCreated gets fired twice, and the second time it's fired is AFTER OnItemDeleted, which means that whatever change I make is overwritten, I suppose. Now how am I supposed to handle that?
Here is working solution (You may want to improve it):
<asp:FormView ID="FormView1" runat="server" DataSourceID="ObjectDataSource1"
AllowPaging="true" OnItemDeleted="FormView1_ItemDeleted" ondatabound="FormView1_DataBound" >
<ItemTemplate>
Key:
<asp:Label ID="KeyLabel" runat="server" Text='<%# Bind("Key") %>' />
<br />
Value:
<asp:Label ID="ValueLabel" runat="server" Text='<%# Bind("Value") %>' />
<br />
<asp:Button ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete" />
<hr />
<asp:Label ID="Label1" runat="server" Text="does not work"></asp:Label>
</ItemTemplate>
</asp:FormView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetList"
DeleteMethod="Delete" TypeName="MyProject.Repository">
<DeleteParameters>
<asp:Parameter Name="key" Type="Int32" />
</DeleteParameters>
</asp:ObjectDataSource>
codebehind:
public string MyProperty { get; set; }
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(MyProperty))
{
Label l = FormView1.FindControl("Label1") as Label;
l.Text = "it works. " + MyProperty;
MyProperty = null;
}
}
protected void FormView1_ItemDeleted(object sender, FormViewDeletedEventArgs e)
{
if (e.Exception != null)
{
MyProperty = e.Exception.Message;
e.ExceptionHandled = true;
}
}
Well, one way is to add another public field to the data source object called "Error", then in MyFormViewItemDeleted change the proper value and re-bind the FormView.
As far as I can see it should work, though there might be easier/more simple way.
Here is how I did after modifying the code a bit. In the code behind, declared a Field in the Class: private string str_feedbackmsg;
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(dbcmd, cnn);
cmd.ExecuteNonQuery();
str_feedbackmsg = "Database Work Done!";
}
catch (SqlException err)
{
str_feedbackmsg = "Database Error: Please Notify the Site Administrators.";
}
finally
{
cnn.Close();
}
Then in the Databound event for the FormView:
protected void gv_main_DataBound(object sender, EventArgs e)
{
if (IsPostBack)
{
Label l = fv_main.FindControl("lbl_feedback") as Label;
l.Text = str_feedbackmsg;
}
}

Resources