Button cannot access text box - c#

My .aspx:
<asp:LoginView runat="server">
<RoleGroups>
<asp:RoleGroup Roles="admin">
<ContentTemplate>
<asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
<asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click" />
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
My code-behind
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
string Mystring = String.Format("{0}", /*I want to put Textbox.text here*/ );
}
}
The problem is that I get a "Textbox" is not defined in the current context. I fiddled around a bit and found that removing the loginview restores the functionality that I want. So why does the loginview break my ability to reference across controls that are in the same view?

C# is case sensitive. Instead of the name Textbox (b is in lower case) use TextBox. Also, I recommend you change the ID of your controls to something more meaningful. Do not set the ID of a TextBox to "TextBox"
Further to your comments, you seem to have your TextBox inside a LoginView. The only way I could get access to this control is
Control container = new Control();
LoginView1.RoleGroups[0].ContentTemplate.InstantiateIn(container);
foreach (Control control in container.Controls)
{
if (control.ID == "txtName")
{
//Phew. Got your control
}
}
Note: I have set the LoginView ID to LoginView1 and TextBox ID to txtName

Try this.TextBox! that should solve the Case Sensitivity thing! also... bad variable naming... As a rule of thumb, do not name a variable exactly like the name of a class...

Related

Get text/value from textbox after value/text changed server side

I have a FormView with data(DataSource,DataBind) that I fill with value='<%# Eval("Name") %>' , but after I'm changing the text in TextBox and press update button I see the same value that before, I cant see new value that I have typed.
What I am missing here?
my html
<asp:FormView ID="MainFormTemplate" runat="server">
<ItemTemplate>
<li class="li_result" runat="server">
<div class="col-3">
<input id="txt_Name" runat="server" value='<%# Eval("Name") %>'>
</div>
</li>
</ItemTemplate>
</asp:FormView>
<asp:Button id="btn_Update" runat="server" OnClick="btn_Update_Click" Text="Update" />
Server side
protected void Page_Load(object sender, EventArgs e)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
public void btn_Update_Click(object sender, EventArgs e)
{
//using System.Web.UI.HtmlControls
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;//i see old value ,not new one that i typed in text box
}
In every postback, you are always getting the old value from your database. The solution is check if the page is being rendered for the first time (!IsPostBack) then set your MainFormTemplate's DataSource else if is being loaded in response to a postback (IsPostBack) get the txt_Name's value like this:
HtmlInputText twt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
else
{
twt = MainFormTemplate.FindControl("txt_Name") as HtmlInputText;
}
}
protected void btn_Update_OnClick(object sender, EventArgs e)
{
string text = twt.Value; // You will get the new value
}
with Page_Load executing every postback, you are always writing value from database (?), and value sent from browser is lost (although still exist in Page.Request.Form member).
In ASP.NET, When a page is submitted, the Page_Load event runs before the button click event. So, the textbox value gets repopulated with its original value before the click event looks at that value.
If this is the situation, then you can wrap the code that assigns the value to the textbox in an if block like this:
if (!IsPostBack)
{
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;
}
Hope this helps you.

How to force enable/disable of controls in aspx?

I have a simple windows form app which I have to migrate to run on a webpage, so I'm trying with aspx(c#).
I have two radio buttons, but at time only one of them should be checked. I implemented the very same code from the original app, but it's not working:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked == true)
{
RadioButton2.Checked = false;
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked == true)
{
RadioButton1.Checked = false;
}
}
So why these changes not being applied on the page?
you can use GroupName Property of RadioButton Control.
if you set the same GroupName for set of RadioButtons you don't need to write the Code Behid which you have written in the above Post/Question, as only one radio button can be selected from the group.
but if you want to invoke some action like Disabling TextBox on Particular Radio Button click event you can use following sample code.
Example: in this example i'm taking 3 Radio Buttons all set to Same GroupName, hence only one RadioButton canbe selected at a time.
when user selects/checks a RadioButton1 i'm Disabling the TextBox1.
Note : Please Make sure that your RadioButton AutoPostBack Property set to True otherwise events on RadioButton won't be fired.
Design Code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RadioButton ID="RadioButton1" runat="server" Text="DisableTextBox" GroupName="Group1" AutoPostBack="True" OnCheckedChanged="RadioButton1_CheckedChanged"/>
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Group1" AutoPostBack="True"/>
<asp:RadioButton ID="RadioButton3" runat="server" GroupName="Group1" AutoPostBack="True" />
Code Behind:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
TextBox3.Enabled = false;
else
TextBox3.Enabled = true;
}
Put the checkboxes in a GroubBox or Panel
You can set the GroupName of both radiobuttons the same, so the Code Behind you wrote is not needed anymore.
Also, check out the RadioButtonList
UPDATE
Your aspx-code should look something like this:
<asp:RadioButton id="RadioButtonEnabled" runat="server" Text="Enabled" GroupName="GroupTxtEnabled" AutoPostBack="True" OnCheckedChanged="RadioButtonEnabled_CheckedChanged"/>
<asp:RadioButton id="RadioButtonDisabled" runat="server" Text="Disabled" GroupName="GroupTxtEnabled" AutoPostBack="True"/>
<asp:TextBox id="TextBox1" runat="server"/>
And in your code-behind:
protected void RadioButtonEnabled_CheckedChanged (object sender, EventArgs e)
{
TextBox1 = RadioButtonEnabled.Checked
}
As you can see, I've used the OnCheckedChanged only at one radiobutton, since both radiobuttons are changed at the same time (property GroupName is equal).

can not read value from dynamically create control

I am stuck with following issue.I've google a lot and try every method but could not solve issue
I am creating control dynamically and after that reading value from dynamically created control
but every time I get error "Object reference is not set to an instance of an object" means I am not able to locate the control even if it available on page.
here is my code
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "myText";
txt.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
Panel1.Controls.Add(txt);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txt = Panel1.FindControl("myText") as TextBox;
Response.Write(txt.Text);
}
Here is aspx page code :
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click"/>
</div>
That's because you create the control when Button1 is clicked, and then try and access it when Button2 is clicked. Dynamic controls must be created on every post back because that state is not maintained. Instead of just building the control in Button1 click, set a flag in Session so you know to rebuild it on Load too. So, in Button1_Click, at the very end of the method, add this line:
Session["BuildMyText"] = true;
and then in Page_Load:
if (Session["BuildMyText"] != null && (bool)Session["BuildMyText"])
{
// build the text box here too
}
and then finally, wrap the construction of the text box in the Button1_Click like this:
if (Session["BuildMyText"] != null && (bool)Session["BuildMyText"])
{
...
}
You need to recreate the control as below:
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox(); //add this line
TextBox txt = Panel1.FindControl("myText") as TextBox;
Response.Write(txt.Text);
}

findcontrol in listview

I want to use FindControl to find the value of the HiddenField i.e hfBlogID. I want to find the value on a ButtonClick
<asp:ListView ID="lvArticle" runat="server">
<LayoutTemplate>
<div runat="server" id="itemPlaceHolder">
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:HiddenField ID="hfBlogID" Value='<%#Eval("BlogID")%>' runat="server" />
<p>
<%#Eval("BlogTitle")%></p>
<p>
<%#Eval("BlogDetails")%></p>
</ItemTemplate>
</asp:ListView>
In order to determine the correct row index you should place your button inside of your ListView.ItemTemplate and handle the ListView.ItemCommand event.
In order to implement this approach you would have to change your code as follows:
<asp:ListView ID="lvArticle" runat="server" OnItemCommand="lv_ItemCommand">
..
<ItemTemplate>
<asp:HiddenField ID="hfBlogID" Value='<%#Eval("BlogID")%>' runat="server" />
<p>
<%#Eval("BlogTitle")%></p>
<p>
<%#Eval("BlogDetails")%></p>
<asp:Button runat="server" CommandName="find" CommandArgument='<%# Eval("yourIDField") %>' />
</ItemTemplate>
...
In code behind:
protected void lv_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "find":
var hidden = e.Item.FindControl("your hidden id") as HiddenField;
break;
}
}
If your button is not inside your ListView, then you would need a way to identify the row you want to extract the hidden value from.
For example, if you allow to select a row in your ListView then you could get the hidden value from the selected row as follows:
protected void find_Click(object sender, EventArgs e)
{
var hidden = this.lv.Items[this.lv.SelectedIndex].FindControl("your hidden ID") as HiddenField;
}
If the button is in the same item template then use ItemCommand event handler and in that handler you can fetch the hidden field directly.
If the button is outside of list view then you need to get the index of item whose hidden field'd value you want to get.
you can use if button is in your listview
var control = (HiddenField)e.Item.FindControl("hfBlogID");
or if button is not in your listvew
var contorl = (HiddenField)this.lvArticle.Items[this.lvArticle.SelectedIndex].FindControl("hfBlogID");
Here you can access the hidden field for each item:
protected void Button1_Click(object sender,EventArgs e)
{
foreach(ListViewDataItem item in lvArticle.Items)
{
HiddenField hf=(HiddenField)item.FindControl("hfBlogID");
}
}
if you have index of item already then you can get it directly like this
HiddenField hf=(HiddenField)lvArticle.Items[index].FindControl("hfBlogID");
Hope this will help..

Can a userControl event cause an update panel to refresh?

I have an aspx.
<div id="headerRegion" class="borderDiv">
<xy:paymentHeader id="paymentHeader1" runat="server" />
</div>
<div id="paymentRegion" class="borderDiv">
<asp:UpdatePanel ID="paymentFormUpdater" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="plcPaymentForm" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
on page init, the placeHolder loads an ascx.
private Control GetPaymentControl(char? coverageBenefitPeriod)
{
Control paymentCtl = null;
switch (coverageBenefitPeriod)
{
case 'L':
paymentCtl = this.LoadControl("~/Controls/Lumpform.ascx");
break;
case 'W':
paymentCtl = this.LoadControl("~/Controls/Periodicform.ascx");
break;
default:
paymentCtl = this.LoadControl("~/Controls/Lumpform.ascx");
break;
}
return paymentCtl;
}
plcPaymentForm.Controls.Add(control);
There's a radioButton List on paymentHeader1 control. When I toggle that radio button would like to elegantly swap between Periodicform.ascx and Lumpform.ascx in the placeholder "plcPaymentForm". How do I do this correctly? I am trying not to load both controls and toggle their visibility. If you have any ideas how to do this properly with minimal page interuption please point me in the right direction.
Thanks,
~ck in San Diego
Little different version of what drs9222 had answered.
1. Declare a delegate
Public delegate void UserControlFormSubmit(object sender, EventArgs e);
2. Declare an event inside user control of type UserControlFormSubmit
Public event UserControlFormSubmit OnFormSubmit;
3. Set User control event as trigger for update panel like this
<asp:UpdatePanel ID="paymentFormUpdater" runat="server" UpdateMode=”Conditional” ChildrenAsTriggers=”true”>
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="plcPaymentForm" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="paymentHeader1" EventName="OnFormSubmit" />
4. Raise the event OnFormSubmit when selectedindexchange event occurs for the radioButtonList. (Note that you need to set AutoPostBack=true for radioButtonList as mentioned by drs9222.
I see three quick and dirty ideas:
You could probably set the radio button list to autopostback and then bubble the event up so that xy:paymentHeader could be used as a trigger for the update panel.
Have xy:paymentHeader raise an event and call the updatepanel's Update method in the event handler.
Pass the updatepanel's id into the control and use find control to find the updatpanel and call its update method.
Example (for #1):
UserControl:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = ((RadioButtonList)sender).SelectedValue;
char? c = null;
if (!string.IsNullOrEmpty(value))
{
c = value[0];
}
RaiseBubbleEvent(this, new CommandEventArgs("SelectedIndexChanged", c));
}
Page:
protected override bool OnBubbleEvent(object source, EventArgs args)
{
if (args is CommandEventArgs)
{
CommandEventArgs cArgs = (CommandEventArgs)args;
if (cArgs.CommandName == "SelectedIndexChanged")
{
Control c = GetPaymentControl((char?)cArgs.CommandArgument);
// ...
updatePanel.Update();
return true;
}
}
return base.OnBubbleEvent(source, args);
}

Categories

Resources