Pass master page control values on content page on page_load - c#

I have a dropdowlist on master page and I want to pass the selected value on content pages when a content page loads. My problem is that the value passes only when I change value on the dropdownlist. So when a page load I have to reselect from dropdownlist to capture the value of the dropdown. If I am browsing the content pages the selected value doesnt pass on page load.
My master page code .net:
<asp:DropDownList ID="ddlcategories"
runat="server" DataSourceID="SqlDataSourcecategories" DataTextField="CategoryName"
DataValueField="CategoryID" AutoPostBack="True"
onselectedindexchanged="ddlcategories_SelectedIndexChanged"></asp:DropDownList>
Master page cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlcategories.DataBind();
ddlcategories.Items.Insert(0, "Uncategorized");
ddlcategories.Items[0].Value = "0";
ddlcategories.SelectedValue = Convert.ToString(Session["lblCategoryID"]);
}
}
protected void ddlcategories_SelectedIndexChanged(object sender, EventArgs e)
{
Session["lblCategoryID"] = Convert.ToInt32(ddlcategories.SelectedValue);
}
Content page cs:
protected void Page_Load(object sender, EventArgs e)
{
Label10.Text = Convert.ToString(((DropDownList)Master.FindControl("ddlcategories")).SelectedValue);
}

Try this solution:
Master page:
<asp:DropDownList ID="ddlcategories" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlcategories_SelectedIndexChanged">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
</asp:DropDownList>
Master page CS:
public string SelectedValue
{
get
{
return ddlcategories.SelectedValue;
}
set
{
ddlcategories.SelectedValue= value;
}
}
protected void ddlcategories_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedValue = ddlcategories.SelectedValue;
}
Content Page markup:
<%# MasterType VirtualPath="~/Site1.Master" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Content page CS.
protected void Page_PreRender(object sender, EventArgs e)
{
Label1.Text = Master.SelectedValue;
}
Note: Values are just to demonstrate, you can use the actual data source values in drop down.

Your issue is as the "ContentPage load" occurs before the "MasterPage load" you don't have access to the dropdownlist items.
to solve this issue you can Bind your drobdownlist first in the master page , but not in the "MasterPage load" , you can Bind it in "MasterPage Init" event which occurs before the "ContentPage Init" and "MasterPage Load" events .
protected void Page_Init(object sender, EventArgs e)
{
ddlcategories.DataBind();
ddlcategories.Items.Insert(0, "Uncategorized");
ddlcategories.Items[0].Value = "0";
ddlcategories.SelectedValue = Convert.ToString(Session["lblCategoryID"]);
}

Related

Find Control in asp:repeater on button click event

I have a dropdown list inside a asp:repeater item template.
how can I get its value on button click event.
<asp:Repeater runat="server" ID="WorkflowListAfter" onitemcreated="WorkflowListAfterItemCreated">
<ItemTemplate>
<asp:DropDownList ID="ddlWorkflowMembers" runat="server" DataTextField="MemberName" DataValueField="MemberID">
</ItemTemplate>
</asp:Repeater>
protected DropDownList ddlWorkflowMembers = new DropDownList();
protected void WorkflowListAfterItemCreated(object sender, RepeaterItemEventArgs e)
{
ddlWorkflowMembers = (DropDownList) e.Item.FindControl("ddlWorkflowMembers");
}
protected void BtnSaveClick(object sender, EventArgs e) {
if (ddlWorkflowMembers.SelectedItem == null) return;
}
the code above is working at first time but after postback ddlWorkflowMembers is always null expersion.
Assuming that BtnSave is also inside the repeater.
You get the RepeaterItem by casting the button's NamingContainer. Then you can use FindControl to get the reference to your DropDownList:
protected void BtnSaveClick(object sender, EventArgs e) {
var btn = (Button)sender;
var item = (RepeaterItem)btn.NamingContainer;
var ddl = (DropDownList) item.FindControl("ddlWorkflowMembers");
// ...
}
If the button is outside of the repeater and you want to save all items, you need to loop through all:
protected void BtnSaveClick(object sender, EventArgs e) {
foreach(RepeaterItem item in WorkflowListAfter.Items)
{
var ddl = (DropDownList) item.FindControl("ddlWorkflowMembers");
// ...
}
}

How to get Text property of TextBox after ItemCommand event

I have a TextBox control inside a panel and this panel is inside DataList ItemTemplate.
After firing the ItemCommand event, everything works fine except that the TextBox.Text property is always an empty string "" although there is some text in it.
I tried several ways but without success. I would really appreciate if someone can assist me with this. Simplified code is shown below.
Thank you!
ASPX page:
<asp:DataList ID="dlDataList" runat="server" onitemcommand="dlDataList_ItemCommand">
<ItemTemplate>
<asp:Panel ID="pnlReply" runat="server" Visible="False">
<asp:TextBox ID="txtTextBox" runat="server"></asp:TextBox><br />
<asp:LinkButton ID="lnkbtnSend" CommandName="Send" runat="server">Send</asp:LinkButton>
</asp:Panel><br />
<asp:LinkButton ID="OpenPanel" CommandName="OpenPanel" runat="server">Open panel</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</asp:Content>
ASPX.CS Page code behind
protected void Page_Load(object sender, EventArgs e)
{
FillDataList();
}
private void FillDataList()
{
List<string> list = new List<string>();
list.Add("First");
list.Add("Second");
list.Add("Third");
dlDataList.DataSource = list;
dlDataList.DataBind();
}
protected void dlDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "OpenPanel")
{
Panel pnlReply = (Panel)e.Item.FindControl("pnlReply");
pnlReply.Visible = true;
}
if (e.CommandName == "Send")
{
TextBox txtTextBox = (TextBox)e.Item.FindControl("txtTextBox");
//I tried this way also..
//TextBox txtTextBox = (TextBox)e.item.FindControl("pnlReady").FindControl("txtTextBox");
Label1.Text = txtTextBox.Text;
}
}
Please use IsPostBack in page load event. Without it your FillDataList(); is executing on every postback and resetting your DataList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDataList();
}
}

How do I delete an item from a ListView using a custom DataSource?

I have a ListView with an IEnumerable<MyDocument> DataSource pulled from a method.
The code in myDocsList_ItemCommand() definitely runs, because the document is actually deleted. My problem is that the ListView still shows the (now deleted) document until the next page refresh, even though I have code to do myDocsList.Items.Remove(dataItem).
The simplified .ascx is basically:
<asp:ListView id="myDocsList" runat="server"
OnItemDataBound="myDocsList_ItemDataBound"
OnItemDeleting="myDocsList_ItemDeleting"
OnItemCommand="myDocsList_ItemCommand">
<LayoutTemplate>
<table>
<asp:Placeholder id="itemPlaceholder" runat="server" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr><td>
<asp:LinkButton
ID="delete" runat="server"
CommandName="Delete" CommandArgument="X"
OnClientClick="javascript:return confirm('...');">
Delete
</asp:LinkButton>
</td></tr>
</ItemTemplate>
</asp:ListView>
The simplified .ascx.cs is basically:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
IEnumerable<MyDocument> docs = getDocuments();
myDocsList.DataSource = docs;
myDocsList.DataBind();
}
}
/* so we have the ID of the document we're deleting later on */
protected void myDocsList_ItemDataBound(object sender,
ListViewItemEventArgs e)
{
var deleteButton =
(LinkButton) ((Control) e.Item).FindControl("delete");
deleteButton.CommandArgument =
((MyDocument) e.Item.DataItem).id.ToString();
}
/* or we get "raised event ItemDeleting which wasn't handled" */
protected void myDocsList_ItemDeleting(Object sender,
ListViewDeleteEventArgs e)
{
}
/* do something here? */
//protected void myDocsList_ItemDeleted(Object sender,
// ListViewDeletedEventArgs e)
//{
//}
protected void myDocsList_ItemCommand(object sender,
ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int docId = int.Parse(e.CommandArgument.ToString());
deleteDocument(docId);
ListViewDataItem dataItem = (ListViewDataItem) e.Item;
myDocsList.Items.Remove(dataItem);
}
}
I've been reading up on the ASP page lifecycle and a few related questions, but I'm reasonably inexperienced with ASP and a bit lost.
How do I get my ListView items to disappear on the PostBack instead of on the next page refresh?
You have to rebound data to your ListView in ItemCommand event, you can change your coding style as below:
//Create a new method for databind
void BindData()
{
IEnumerable<MyDocument> docs = getDocuments();
myDocsList.DataSource = docs;
myDocsList.DataBind();
}
//Call databind method in your prerender event
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
//Again bind data after delete operation
protected void myDocsList_ItemCommand(object sender,
ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int docId = int.Parse(e.CommandArgument.ToString());
deleteDocument(docId);
BindData();
}
}

Image.ImageUrl not working (C#, asp.net)

I have the next code:
<asp:ListView ID="LV1" runat="server" DataSourceID="LinqDataSource">
<ItemTemplate>
<asp:Image ID="Image1" Width="100px" Height="100px" runat="server" />
//....and so on till the
</asp:ListView>
The code behind:
protected void checkTheImage()
{
foreach (ListViewItem item in LV1.Items)
{
((Image)item.FindControl("Image1")).ImageUrl = "~/noImage.jpg";
}
}
And page load:
protected void Page_Load(object sender, EventArgs e)
{
checkTheImage();
}
The problem is - the noImage.jpg is not display... why ?
not sure if your markup is ok, you should also have a closing ItemTemplate tag somewhere... please update your markup.
just to try out things, does it work if you move the call of checkTheImage(); inside the Page_PreRender?
is there any place where you DataBind the ListView in your page life cycle?
May be you need to rebind the ListView.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LV1.DataBind();
checkTheImage();
}
}

No Change for Index of DropDownList in a Custom Control!

I have Created A Custom Control which is a DropDownList with specified Items. I designed AutoPostback and SelectedCategoryId as Properties and SelectedIndexChanged as Event for My Custom Control.
Here Is My ASCX file Behind Code:
private int _selectedCategoryId;
private bool _autoPostback = false;
public event EventHandler SelectedIndexChanged;
public void BindData()
{
//Some Code...
}
protected void Page_Load(object sender, EventArgs e)
{
BindData();
DropDownList1.AutoPostBack = this._autoPostback;
}
public int SelectedCategoryId
{
get
{
return int.Parse(this.DropDownList1.SelectedItem.Value);
}
set
{
this._selectedCategoryId = value;
}
}
public string AutoPostback
{
get
{
return this.DropDownList1.AutoPostBack.ToString();
}
set
{
this._autoPostback = Convert.ToBoolean(value);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectedIndexChanged != null)
SelectedIndexChanged(this, EventArgs.Empty);
}
I Want Used Update Panel to Update Textbox Fields According to dorp down list selected index.
this is my code in ASPX page:
<asp:Panel ID="PanelCategory" runat="server">
<p>
Select Product Category:
<myCtrl:CategoryDDL ID="CategoryDDL1" AutoPostback="true" OnSelectedIndexChanged="CategoryIndexChanged"
SelectedCategoryId="0" runat="server" />
</p>
<hr />
</asp:Panel>
<asp:UpdatePanel ID="UpdatePanelEdit" runat="server">
<ContentTemplate>
<%--Some TextBoxes and Other Controls--%>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="CategoryDDL1" />
</Triggers>
</asp:UpdatePanel>
But Always The Selected Index of CategoryDDL1 is 0(Like default). this means Only Zero Value will pass to the event to update textboxes Data. what is the wrong with my code? why the selected Index not Changing? Help?
If your BindData() method is completely self-contained, move that from Page_Load to:
protected override void OnInit(EventArgs e)
{
BindData();
}
This will keep your dropdown list in your control from being rebound on every page load, which I assume is the problem from the code that you've posted.
If, however, your BindData() method requires information from the parent page, change the page load to:
protected void Page_Load(object sender, EventArgs e)
{
if(!this.Page.IsPostback) {
BindData();
}
DropDownList1.AutoPostBack = this._autoPostback;
}
This will allow your dropdown to be bound only on the first page load, and subsequent loads should be able to access the properties correctly.
Also, be sure to check your ASPX page to make sure you're not binding the ASCX control on every page load. This can be resolved in the same way on the parent page.

Categories

Resources