DropDownList selected value lost on postback - c#

On my page, i'm losing my dropdownlist's selected value on postback.
This is my aspx code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ProjectSearch.aspx.cs" Inherits="Site.Templates.ProjectSearch" MasterPageFile="~/Site/Templates/Framework/Base.master"
EnableViewState="true"%>
<asp:Content ID="Content1" ContentPlaceHolderID="Content" runat="server">
<div>
<ul>
<li class="filter">
<asp:DropDownList runat="server" ID="m_Filter" CssClass="form-control"/>
</li>
<li class="button">
<asp:LinkButton class="button-dark-orange" ID="m_search" runat="server" OnClick="m_search_click" >
Click
</asp:LinkButton>
</li>
</ul>
</div>
And in my code-behind there's nothing other than button click.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindDropdown();
}
}
public void BindDropdown()
{
try
{
List<int> ds = Filter.GetData()
m_filter.DataSource = ds;
m_Filter.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void m_search_click(object sender, EventArgs e)
{
Response.Write(m_Filter.SelectedIndex);
}
It always writes 0. Any help?

only add few things
<asp:DropDownList runat="server" ID="m_Filter" CssClass="form-control" AutoPostBack="true" />
write belove code in code behind file
ddlproduct.DataSource = your method;
ddlproduct.DataTextField = "text";
ddlproduct.DataValueField = "value";
ddlproduct.DataBind();

Related

How can update usercontrol in masterpage

I have a master page and an user control on it.
I have a two buttons in the user control for create or remove session, and a label that shows a session text, when click the buttons nothing happens and user control doesn't update I should refresh the page,
Would you please anybody help me to fix this issue ?
This is my master page markup:
<form runat="server">
<div>
<!--previous codes-->
<nav class="navigation">
<div class="wrapper">
<controller:menu runat="server" ID="menu" />
<controller:user runat="server" ID="user" />
</div>
</nav>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<!--Next Codes-->
</div>
</form>
and this is my user control
<ul class="nav signup">
<li class="no-drop-down">
<asp:Label ID="_signupbutton" runat="server" CssClass="sr">Test</asp:Label>
<div class="signup-dropdown">
<asp:PlaceHolder ID="_defaultuser" runat="server" Visible="false">
<div class="notloggeduser">
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="usercontroller"
OnClick="LinkButton1_Click" Text="????">
</asp:LinkButton>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="_signedup" runat="server" Visible="false">
<div class="defaultuser">
<ul>
<li>
<asp:LinkButton ID="_userlogout" runat="server" CssClass="usercontroller" OnClick="_userlogout_Click">
<i class="fa"></i>????
</asp:LinkButton>
</li>
</ul>
</div>
</asp:PlaceHolder>
</div>
</li>
</ul>
and this is user control codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["signup"] == null)
{
_signupbutton.Text = "??? ??? / ????";
_defaultuser.Visible = true;
}
else
{
_signupbutton.Text = "<i class=\"fa\"></i> " + Session["signup"].ToString();
_signedup.Visible = true;
}
}
}
protected void _userlogout_Click(object sender, EventArgs e)
{
Session.Remove("signup");
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session.Add("signup", "????? ??????????");
}
Your order of events is a bit messed up here.
Page_Load will execute before the event handlers for the click events. You need to perform the setup of the button state from the event handlers, as if you do it in page load your session object wont have been updated yet.
You will need to do a few things here (this isn't tested but should show you the logic):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // This will run when the page is loaded but not from a post back / button click etc (e.g. from your page refresh)
{
this.SetButtonState();
}
else
{
// use this for things you want to happen on postback only
}
}
private void SetButtonState()
{
if (Session["signup"] == null)
{
_signupbutton.Text = "??? ??? / ????";
_defaultuser.Visible = true;
}
else
{
_signupbutton.Text = "<i class=\"fa\"></i> " + Session["signup"].ToString();
_signedup.Visible = true;
}
}
protected void _userlogout_Click(object sender, EventArgs e)
{
Session.Remove("signup");
// Update your button state
this.SetButtonState();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session.Add("signup", "????? ??????????");
// Update your button state
this.SetButtonState();
}

Text property of a TextBox is empty when an async PostBack occurs

I've had a look at lots of posts and I feel like I'm going crazy as nothing I've tried seems to work. I simply want to click a button and retrieve the value of a textbox.
I'm using web forms with a site.master so not sure if this could be affecting the problem, but most of the solutions I've seen don't appear to be using a site.master.
I'm not binding the textbox, initially I just wanted to create a contact form.
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="Blackburn_Pulse.About" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>$("#menuAbout").addClass("navi-active");</script>
<div class="contentBody">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="tb_Test" EnableViewState="true" CausesValidation="false" runat="server"></asp:TextBox>
<asp:LinkButton ID="btn_Test" runat="server" OnClick="btn_Test_Click" Text="send test" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn_Test" EventName="click" />
</Triggers>
</asp:UpdatePanel>
</div>
</asp:Content>
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Master.EnableViewState = true;
if (IsPostBack)
{
var test_var = tb_Test.Text; //returning empty
}
}
protected void btn_Test_Click(object sender, EventArgs e)
{
var test_var = tb_Test.Text; //returning empty
}
}
UPDATE:
site.master.cs
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCategories();
}
}
protected void BindCategories()
{
Categories Categories = new Categories();
rpt_categories.DataSource = Categories.Get_Categories();
rpt_categories.DataBind();
}
protected void lb_newsCat_Command1(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "naviTo":
//Redirect user to selected category
Response.Redirect("~/" + e.CommandArgument.ToString());
break;
}
}
}
I'm converting a PHP website to an ASP.net website. Turns out I had another HTML form tag on a search box that I haven't started working on yet.
Unfortunately the debugger doesn't throw an error if you have another form tag so anybody else who's just spent hours of their lives searching, double check you don't have more than 1 form tag!
In my site.master.aspx file, I had a search box as follows:
<form method="post" action="?">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
</form>
Once I took the extra form tag out, everything worked fine.

Read textBox from dynamically created

I am trying to create a textbox dynamically using a string. and then trying to read on a buttton click.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="textboxtest.aspx.cs" Inherits="test2.textboxtest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="TextBoxDiv" runat="server" class="asid box">
</div>
<asp:Button ID="Button1" runat="server" Text="CreateTextBox" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="ReadTextBox" onclick="Button2_Click" />
</asp:Content>
Here is the code behind.
protected void Button1_Click(object sender, EventArgs e)
{
string finalText = #"<input type=""text"" ID=""T1"" runat=""server"">
<asp:TextBox ID=""TB1"" runat=""server""></asp:TextBox>";
TextBoxDiv.InnerHtml = finalText;
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txtAddress2 = (TextBox)Page.FindControl("TB1");
foreach (Control c in TextBoxDiv.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
string str = txt.Text;
}
}
}
As you can see from the code i have tried to access the textbox using find control and also looping through. but both are failing.
I managed to get it to work, but by only having to create dynamic textboxes in Page_Init event. So every time there is a post back you need to re-create your dynamic controls. You can check online, they say the same thing.
So here is the client side:
<asp:PlaceHolder runat="server" id="TextBoxesHere" />
<asp:Button ID="Button1" CssClass="btn btn-primary btn-outline" runat="server"
Text="CreateTextBox" OnClick="Button1_Click" />
<asp:Button ID="Button2" CssClass="btn btn-primary btn-outline" runat="server"
Text="ReadTextBox" OnClick="Button2_Click" />
Server Side:
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "T1";
txt.CssClass = "form-control";
TextBoxesHere.Controls.Add(txt);
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "T1";
txt.CssClass = "form-control";
TextBoxesHere.Controls.Add(txt);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)TextBoxesHere.FindControl("T1");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + txt.Text + "');", true);
}
use a Placeholder instead of a div (it will generate a div) and then add controls in the placeholder instead of using InnerHtml.
So this can be achieved like this:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="textboxtest.aspx.cs" Inherits="test2.textboxtest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:PlaceHolder runat="server" ID="TextBoxPlaceHolder"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="CreateTextBox" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="ReadTextBox" onclick="Button2_Click" />
</asp:Content>
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
string finalText = #"<input type=""text"" ID=""T1"" runat=""server"">";
var textbox = new TextBox();
textbox.ID = "TB1";
this.TextBoxPlaceHolder.Controls.Add(new LiteralControl(finalText));
this.TextBoxPlaceHolder.Controls.Add(textbox);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txtAddress2 = (TextBox)Page.FindControl("TB1");
foreach (Control c in TextBoxDiv.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
string str = txt.Text;
}
}
}

Unable to get textbox even when ID is defined

I am currently creating a page that a user will be able to input information and on submit it should save this information to a text file, however I seem to be unable to obtain the textbox as it appears to be undefined even when an ID is set on it, could someone please explain what I am doing wrong? As it seems to be working correctly with my btnSave method.
Backend C#:
public partial class Green_FreeShipping : System.Web.UI.Page
{
private static readonly string FILE_PATH = "~/TextFiles/Notes.txt";
private void GetNote()
{
using (TextReader tr = new StreamReader(MapPath(FILE_PATH)))
{
txtNote.Text = tr.ReadToEnd();
}
}
private void SaveNote()
{
using (TextWriter tw = new StreamWriter(MapPath(FILE_PATH)))
{
tw.Write(txtNote.Text);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetNote();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
this.SaveNote();
this.GetNote();
}
}
ASP.NET code:
<%# Page Language="C#" MasterPageFile="~/admin/masters/admin.master" autoeventwireup="true" inherits="TextBox_ReadWriteToTextFile" Title="Green & Free shipping amounts" codefile="~/admin/bespoke/Green-FreeShipping.aspx.cs"%>
<%# Register TagPrefix="web" Assembly="website.Web" Namespace="website.Web" %>
<%# Register TagPrefix="sales" Assembly="website.site.Web" Namespace="website.site.Web.Sales" %>
<%# Register TagPrefix="ecom" Namespace="website.site.Web" Assembly="website.site.Web" %>
<asp:Content ID="TitleContent" ContentPlaceHolderID="TitlePlaceHolder" runat="Server">
<title>Shopfront - Green and Free shipping amounts</title>
</asp:Content>
<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
<div style="margin-bottom: 20px;">
<asp:textbox id="txtNote" runat="server" rows="5" textmode="MultiLine" width="200px" />
</div>
<asp:button id="btnSave" runat="server" onclick="btnSave_Click" text="Save" />
</asp:content>
Your asp should inherit 'Green_FreeShipping' so that the c# can have access to the controls contained in it.

C# Dynamically filled DropDownList resets on button OnClick

I am having a bit of a DUH moment and need some help. I have a DropDownList control that gets filled with values on page load and a submit button that does further manipulations. However, when the button is clicked DropDownList returns a value of "-1" and not of the selected option. What is wrong here?
Web page:
<%# Page Language="C#" MasterPageFile="/new/MasterPageA2.master" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Checkout.aspx.cs" Inherits="Common_Checkout" EnableViewState="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="test11"></asp:Label>
<asp:DropDownList ID="ddlbillingcountry" required="true" EnableViewState="true" runat="server"></asp:DropDownList>
<asp:Button ID="ImageButton1" AlternateText="Proceed" OnClick="ImageButton1_Click" CausesValidation="false" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<p>Loading...</p>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
PopulateCountry(ddlbillingcountry);
}
}
private void PopulateCountry(DropDownList Controlname) {
DatasetTableAdapters.CountryTableAdapter _CountryTableAdapter = new DatasetTableAdapters.CountryTableAdapter();
Controlname.ClearSelection();
Controlname.Items.Clear();
DataTable _DataTable = _CountryTableAdapter._Eco_Country_Select();
Controlname.DataSource = _DataTable;
Controlname.DataTextField = "CountryName";
Controlname.DataValueField = "Country";
Controlname.DataBind();
Controlname.Items.Insert(0, new ListItem("- Select Country -", ""));
}
protected void ImageButton1_Click(object sender, EventArgs e) {
test11.Text += "<p>clicked " + ddlbillingcountry.SelectedIndex + " - " + ddlbillingcountry.SelectedValue.ToString();
}
You could set the datasource property to the name of a function which returns a dataset.
Try datasource='<%# PopulateCountry("ddlbillingcountry") %>' but you will need to change or overload the function to change the argument to a string, remembering to set the datavaluefield and datatextfield.Or you may want to create a separate function and call that with no arguments.

Categories