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);
}
Related
I have a button whose text (a counter on datatable) should be changed when I click Update or Add button.
But it doesn't. It only does when I refresh the page only, why ?
Button are within UpdatePanel.
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = ShowLastHearingDates();
if (dt.Rows.Count > 0)
{
btnShowLasthearingDates.Text = dt.Rows.Count.ToString();
}
update:
protected void btnupdate_click(object sender, Eventargs e)
{
if (MngCaseHearings.UpdateCaseANDHearingDetails(CaseNo, CaseTitle))
{
btnUpdate.Visible = false;
btnAddCaseAndHearingDetails.Visible = true;
}
}
Problem is that the page load event happens before your update occurs. You can put the code in the page prerender event which will be hit after the page load and control event
try to put UpdateMode to "always"
or put all related control in the samne panal
or put AsyncPostBackTrigger
this urls my help
https://msdn.microsoft.com/en-us/library/bb386454.aspx
http://code.runnable.com/UhmIdrdIZy9aAATR/how-to-use-updatepanel-in-asp-net
In my Sharepoint 2010 app, I'm handling most events client-side with jQuery. However, for the saving of data to the Sharepoint list, and the generation of a PDF file with that data, I want to handle that server-side, with C#.
I tried to invoke a C# event this way:
0) Aded an HTML button in my project's *.ascx file:
<button type="button" name="saveData" id="saveData">Save Data</button>
1) Added jQuery to respond to that button being clicked (in the same *.ascx file):
$("#saveData").click(function () {
$('#hiddenSave').trigger('valuechanged');
});
2) Created a hidden element in the server-side C# (in the *.ascx.cs file):
HiddenField hiddenSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
hiddenSave = new HiddenField();
hiddenSave.ID = "hiddenSave";
hiddenSave.ValueChanged += new EventHandler(hiddenSave_ValueChanged);
this.Controls.Add(hiddenSave);
}
protected void hiddenSave_ValueChanged(object sender, EventArgs e)
{
GeneratePDF();
}
private void GeneratePDF()
{
;//bla
}
But I never reach the "ValueChanged" event handler; $("#saveData").click() fires, but not hiddenSave_ValueChanged().
So do I need a tweak to this, or a completely different approach? How can I do as much as possible client-side with jQuery, but also run server-side/C# code where necessary, in a Sharepoint 2010 app?
UPDATE
A little more detail, and about additional things I've tried: I'm creating a button on a Sharepoint page dynamically (in C#) in my *.ascx.cs file:
Button btnSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
btnSave.Visible = false;
this.Controls.Add(btnSave);
}
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Text = "You clicked me!";
PostTravelData ptd = new PostTravelData();
}
I set it visible at the right time in the client-side jQuery in the *.ascx file:
$('#btnSave').show();
However, clicking the button does not reach the btnSave_Click() event - the breakpoint there is never reached, nor is the button's text changed. Why not?
Even when I don't set the button invisible (comment out the "btnSave.Visible = false;" line), the click handler isn't reached...is Page_Load() too late? Is there an earlier page event I can use that would work?
I tried moving it from Page_Load() to OnPreRender(), too, like this:
protected void OnPreRender(EventArgs e)
{
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
//btnSave.Visible = false;
this.Controls.Add(btnSave);
}
...(and OnRender()) but the button doesn't even display...
And, trying a different tack, I commented out the dynamic creation server-side code and tried to attach to a button created in the HTML (*.ascx file):
<button type="button" name="saveData" id="saveData" runat="server" onclick="saveData_Click">Save Data</button>
(by adding the "runat server" and the onclick handler), and then adding this "code-behind" (*.ascx.cs)):
protected void saveData_Click(object sender, EventArgs e)
{
PostTravelData ptd = new PostTravelData();
SaveToList(ptd);
GeneratePDF(ptd);
}
...but there was still no joy in Mudville -- the breakpoint in the handler is not reached.
Yet another attempt was:
In the *.ascx:
<asp:Button runat="server" id="saveData" name="saveData" onclick="saveData_Click" Text="Bla" />
In the code-behind:
saveData.Click += saveData_Click;
The "Bla" button is created, but clicking on it reaches not the breakpoint in the "saveData_Click" handler.
I even adapted some code from here like so:
Button btnSave = null;
. . .
protected override void CreateChildControls()
{
btnSave = new Button();
btnSave.Width = new Unit(150, UnitType.Pixel);
btnSave.Text = "Can you see me?";
btnSave.Click += new EventHandler(btnSave_Click);
Controls.Add(btnSave);
}
...but I still do not reach the "protected void btnSave_Click(object sender, EventArgs e)" handler when I click the button.
Surely there's a way to get a handle on the button server-side and manipulate it (specifically, respond to its click event)...?!?
First of all, as far as I know, there is no such event for input type hidden in a ascx page. If you create the input type hidden with runat server in the ascx code then you'll see that when you try to add this event it's not available. However there are other events like OnClick that you can simulate to get the desired result.
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();
}
I use a gridview to display the search result. After clicking search button, the gridview will show page 1, but when I click page 2 link, the gridview disappeared and it was back when I click search button again and show page 2's content.
here is my code
<asp:GridView ID="searchresult" runat="server" AutoGenerateColumns="true" AllowPaging="true" OnRowDataBound="searchresult_RowDataBound" OnPageIndexChanging="searchresult_PageIndexChanging"
HeaderStyle-BackColor="#f9e4d0"
HeaderStyle-Height="20px"
Font-Size="11px"
AlternatingRowStyle-BackColor="#cfdfef"
Width="800px" style="text-align:left">
</asp:GridView>
and code behind
protected void search_Click(object sender, EventArgs e)
{
List<someclass> totalResult = new List<someclass>();
..... //some code to generate the datasource
searchresult.DataSource = totalResult;
searchresult.AllowPaging = true;
searchresult.DataBind();
}
protected void searchresult_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void searchresult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
searchresult.PageIndex = e.NewPageIndex;
DataBind();
}
I have no idea why the page 2 won't show up until I click search button again. when I clicked the page 2 link, the page did postback but the RowDataBound event was not fired
You have to give your grid a datasource. It appears you are only doing this on search_Click, so your grid is only going to have data then. Try something like:
protected void search_Click(object sender, EventArgs e)
{
PopGrid();
}
protected void searchresult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
searchresult.PageIndex = e.NewPageIndex;
PopGrid();
}
protected void PopGrid()
{
List<someclass> totalResult = new List<someclass>();
..... //some code to generate the datasource
searchresult.DataSource = totalResult;
searchresult.AllowPaging = true;
searchresult.DataBind();
}
searchresult_PageIndexChanging event handler will make that functionality work. However I recommend you use a gridview control inside a Panel with vertical scroll bar. My user love it and it is a lot faster moving up and down the gridview without defining any page index changing.
I hope it work for you.
I have a table with all the objects I have in my db. I load them in my Page_Load function. I have a text field and a button that when clicking the button, I want the handler of that click to put a new object with the name written in the text field in the db.
Now, I want that what happens after the click is that the page loads again with the new item in the table. The problem is that the button event handler is run after the Page_Load function.
A solution to this would be to use IsPostBack in the Page_Load or use the pre load function. A problem is that if I would have 3 different buttons, I would have to differ between them there instead of having 3 different convenient functions.
Any solutions that don't have this problem?
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
// LOAD DATA FROM DB
}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
}
Maybe you should try loading your data during PreRender instead of Load
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += Page_PreRender
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
}
protected bool reloadNeeded {get; set;}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
reloadNeeded = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(reloadNeeded || !IsPostBack)
// LOAD DATA FROM DB
}
You can check the event target and do what you need then:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = Page.Request.Params["__EVENTTARGET"];
if(whatever)
{
//do your logic here
}
}
}
Get control name in Page_Load event which make the post back
Use the Page_PreRenderComplete event to retrieve your table. That way your page will always have the most recent data available after all user events have fired.
Why don't you move what you have in the click event into a new method. Then call that method as the first line in your page load?
An old question but I faced the same problem in my C#/ASP.NET Website with master/content pages: a click on a link on the master page should change a query parameter for a gridview on the content page. As you stated the button click event is handled after Page_Load. But it is handled before Page_LoadComplete (see the information about ASP.NET Page Life Cycle), so you can change the page content there.
In my case I solved the problem by setting a session variable in the click event in the master page, getting this variable in the Page_LoadComplete event in the content page and doing databind based on that.
Master page:
<asp:LinkButton ID="Btn1" runat="server" OnCommand="LinkCommand" CommandArgument="1" >Action 1</asp:LinkButton>
<asp:LinkButton ID="Btn2" runat="server" OnCommand="LinkCommand" CommandArgument="2" >Action 2</asp:LinkButton>
protected void LinkCommand(object sender, CommandEventArgs e)
{
HttpContext.Current.Session["BindInfo", e.CommandArgument.ToString());
}
Content page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string BindInfo = HttpContext.Current.Session["BindInfo"].ToString();
YourBindDataFunction(BindInfo);
}