I create some dynamic controls eg: TextBox.
These a created in a ModalPopupExtender and are created after a ButtonClick.
protected void AddGroupBTN_Click(object sender, EventArgs e)
{
GroupMPE.Show();//GroupMPE is a ModalPopupExtender
ScheduleIdHF.Value = 1; //ScheduleIdHF is a HiddenField declared in the .aspx page
CreateControls(ScheduleIdHF.Value);
...
}
private void CreateControls(string ScheduleId)
{
TableRow TR = new TableRow();
TR.ID = "tableRow1";
TableCell TC = new TableCell();
TC.ID = "tableCell1;
TextBox textBox = new TextBox();
textBox.ID = "textBox1";
TC.Controls.Add(textBox);
TR.Cells.Add(TC);
ExampleTable1.Rows.Add(TR);//ExampleTable1 is declared in the .aspx page
}
Then when another button is clicked I want to recreate these controls on Page_PreInit like this.
protected void Page_PreInit(object sender, EventArgs e)
{
if(IsPostBack)
{
if (!string.IsNullOrEmpty(ScheduleIdHF.Value))
{
CreateControls(ScheduleIdHF.Value);
...
However I want the method call to CreateControls to be conditional on and using the value of the HiddenField ScheduleIdHF. The problem is that the HiddenField is null and is not created to after the Page_PreInit event. Does anybody have any solutions to solve this conundrum? Because I want to get the text of the TextBox after postback.
You can easily access the textbox/hiddenfield value using the following code. This is just using basic web programming idea that anything posted to server is available in Request object.
Code-behind to access control values in PreInit event
protected void Page_PreInit(object sender, EventArgs e)
{
if(Page.IsPostBack) {
var x = Request[TextBox1.UniqueID];
var y = Request[ScheduleIdHF.UniqueID];
//use values of x and/or y to implement your logic
if(y != null && y == "somevalue") {
//your custom logic goes here
}
}
}
Textbox markup
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:HiddenField ID="ScheduleIdHF" runat="server" Value="1010"/>
Use a Session variable to store the value of the HiddenField and then retrieve it in the PreInit event, like:
protected void Page_PreInit(object sender, EventArgs e)
{
if (IsPostBack)
{
string ScheduleIdHF = string.Empty;
if (Session["ScheduleIdHF"] != null)
{
ScheduleIdHF = Session["ScheduleIdHF"].ToString();
CreateControls(ScheduleIdHF);
...
}
}
}
Related
I would like to select the gridview and redirect to the next page where username in gridview passed to the text box in the next page when the row is being clicked. How do i do that?
My code behind (on the first page):
protected void GridView1_OnRowSelected(object sender, GridViewSelectEventArgs e)
{
var username = Convert.ToString(GridView1.DataKeys[e.NewSelectedIndex].Value);
Response.Redirect("ViewUploads.aspx?USERNAME=" +username);
}
My code on the second page:
protected void TextBoxUsername_TextChanged(object sender, EventArgs e)
{
var username = Request.QueryString["USERNAME"];
}
I assume that you're looking for the SelectedIndexChanged event of the GridView.
protected void GridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
var username = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
Response.Redirect("ViewUploads.aspx?USERNAME=" +username);
}
In the next page(ViewUploads.aspx) you need to assign it to the TextBox' Text:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack && Request.QueryString["USERNAME"] != null)
this.txtUserName.Text = Request.QueryString["USERNAME"];
}
I'm not sure if you have already done that, if you want to use the DataKeys-collection in the first page, you have to set the DataKeyNames property accordingly. For example:
<asp:gridview id="GridView1"
datakeynames="UserName"
onselectedindexchanged="GridView_SelectedIndexChanging"
runat="server">
...
</asp:gridview>
Is there anyway to raise a RadioButton checked routed event from code, in order to handle it in a parent control?
This is the situation:
var radio = new RadioButton();
radio.IsChecked = true;
radio.RaiseEvent(new RoutedEventArgs(RadioButton.CheckedEvent));
The third line does not work.
Googling, I found another way based on the RadioButtonAutomationPeer, but I had not found a way to make it work.
Does someone have some hint?
Thanks in advance.
var radio = new RadioButton();
radio.CheckedChanged +=new EventHandler(radio_CheckedChanged);
radio.IsChecked = true;
private void radio_CheckedChanged(object sender, EventArgs e)
{
if (radio.Checked)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
}
}
You can get Radio checked event programmatically but not directly add on page/form.
you have to create panel or some else controler in which you can add this Radio Button like this
this is your .aspx page
<div>
<asp:Panel runat="server" ID="pnl1">
</asp:Panel>
</div>
this is your aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
var radio = new RadioButton { Checked = false, AutoPostBack = true, Text = "Click" };
radio.CheckedChanged += radio_CheckedChanged;
pnl1.Controls.Add(radio);
}
void radio_CheckedChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
HTML
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button runat="server" ID="show" OnClick="show_Click" Text="show"/>
<asp:Button runat="server" ID="add" OnClick="add_Click" Text="add new "/>
<div id="content" runat="server"></div>
</asp:Content>
code
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Checked);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}
by button add added a new checkbox on runtime.
then i want get checkbox chb by button show
but ((CheckBox) content.FindControl("chb")).Checked return Null.
i want add checkbox dynamically and then checked that which of them checked is true.
This happens because dynamically added controls are not preserved after postbacks. You can easily demonstrate this by adding another button (without a click event handler) to the page. Run the application and click the "add" button to create the checkbox, then click the newly added button and the checkbox will be gone after the postback.
Well, I can not understand what you are trying to achieve but;
protected void show_Click(object sender, EventArgs e)
{
Response.Write((Session["chb"] as CheckBox).Text);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
Session["chb"] = chb;
}
Your events don't happen in the same postback of your page - when you click add, it adds the checkbox but then the page execution finishes, the page is sent to the client and it's done with handling that Click event.
When you then click the show button, it's another postback, in which your checkbox has not been created, so it doesn't exist.
To handle this, you have a few options:
1.
Add the checkbox to the page in the designer and set its Visible property to false inially. You can keep the add button, but it won't actually add a checkbox to the page, it'll just make it visible by setting Visible to true.
2.
If you really want to dynamically add the checkbox, then you need to add it every time the page is executed, in one of the page event handlers (for example Load). The way to do that is to save a value in the viewstate or in a hidden field when you click add and based on the value, you'd create the checkbox on subsequent postbacks.
protected void Page_Load (object sender, EventArgs e)
{
if ( IsPostBack )
{
if ( Session["chb"] != null )
CreateChb ();
}
}
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Text);
}
protected void add_Click(object sender, EventArgs e)
{
Session["chk"] = true;
CreateChb ();
}
private void CreateChb ()
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}
I am trying to assign a ViewState value in my application with a SelectedIndexChanged function. Once it's assigned the postback will use the value to change some data and then set the value to zero but I can't seem to get it to work correctly. The controls are all created dynamically on Page_Load.
Page Load
protected void Page_Load(object sender, EventArgs e)
{
CreateAttributeControls();
TempProductVariantId = 0;
}
Create Attribute Controls
public void CreateAttributeControls()
{
...
var ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.SelectedIndexChanged += new EventHandler(ArtistArtwork_SelectedIndexChange);
ddlArtistArtworks.AutoPostBack = true;
...
}
ArtistArtwork_SelectedIndexChange
protected void ArtistArtwork_SelectedIndexChange(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
TempProductVariantId = int.Parse(ddl.SelectedValue);
}
TempProductVariantId ViewState Save
public int TempProductVariantId
{
get
{
if (ViewState["TempProductVariantId"] == null)
return 0;
else
return (int)ViewState["TempProductVariantId"];
}
set
{
ViewState["TempProductVariantId"] = value;
}
}
When I load the page everything is fine. I change the DropDownList's value, It posts back, and the value is not set. Change it again the value is set and continues to change as I change the value of the DropDownList.
Any guidance on this would be greatly appreciated.
Note: I have tried changing when CreateAttributeControls() is called. In OnPreRender for example. I was given this to understand the lifecycle of the page Life Cycle
That's because you are essentially recreating the dropdown on every postback..
try this
public void CreateAttributeControls()
{
...
DropDownList ddlArtistArtworks;
if (!IsPostBack)
{
ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.AutoPostBack = true;
}
else
{
ddlArtistArtworks = (DropDownLise)divAttribute.FindControl("ddlArtistArtworksTest");
}
ddlArtistArtworks.SelectedIndexChanged += new EventHandler(ArtistArtwork_SelectedIndexChange);
...
}
For dynamically added controls, the event handler has to be linked up everytime so that has to be done outside the if-block, unconditionally.
I have this weird problem when putting textboxes on the page in reverse. The whole event system is messed up. Changing one textbox fires TextChange on all textboxes. I can fix this by putting the controls in a list first and then call add while iterating trough the list in reverse. But i just want to know why this fails. Heres some code (.net 2.0)
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
InitFields();
}
private void InitFields()
{
int nrFields;
//We have a static textbox called nrElements, this determines the number
//of fields to initialize
if (int.TryParse(nrElements.Text, out nrFields))
{
//Put all the dynamic fields on the screen in reverse order
foreach(Control t in GetDynamicFields(nrFields))
{
//Calling Controls.Add works fine
//Calling Controls.AddAt messes up the events
//Try changing different textboxes
plhFields.Controls.AddAt(0, t);
}
}
}
private IEnumerable<Control> GetDynamicFields(int nrFields)
{
for (int i = 0; i < nrFields; i++)
{
TextBox txtBox = new TextBox();
txtBox.ID = string.Format("dynTextBox{0}", i.ToString());
txtBox.AutoPostBack = true;
txtBox.TextChanged += t_TextChanged;
yield return txtBox;
}
}
private void t_TextChanged(object sender, EventArgs e)
{
TextBox txtBox = sender as TextBox;
if (txtBox != null)
txtBox.Text = txtBox.Text + "Changed ";
}
}
Try calling InitFields() on the Page_PreInit event rather than Page_Load.
Or an alternative would be to override the CreateChildControls() method (MSDN Article), if you use CreateChildControls() you'll need to call EnsureChildControls() on the Page_Load method to make sure the CreateChildControls() method has been called before you try to access any controls which have been created within that method.
Always put dynamic controls in OnInit event. Then viewstate serializer/deserializer will work. And you have to add controls on every request, not just in !IsPostBack.