How to change button's onclientclick property server side? - c#

I have a button as follows:
<asp:Button ID="btnNext" runat="server" Font-Bold="true" Text="Next"
onclick="btnNext_Click" style="text-align: center" Width="80px" />
and a RadNumericTextBox:
<telerik:RadNumericTextBox ID="txtTotal5" runat="server" Width="50px" AutoPostBack="true"
MinValue="0" ontextchanged="txtTotal5_TextChanged"><NumberFormat DecimalDigits="0" /></telerik:RadNumericTextBox>
I need to set the onClientClick property based on whether a telerik RadNumericTextBox has text in it or not. If it does not have a value, the onClientClick property needs to be set as shown below. If there is a value in the box, I want to just go on to the onclick event which directs it to the next form.
protected void txtTotal5_TextChanged(object sender, EventArgs e)
{
if (txtTotal5.Value.ToString() == "")
{
btnNext.OnClientClick = "javascript: return confirm('Please have the employee complete this form.')";
}
else
{
btnNext.OnClientClick = "";
}
}
Now I have used the debugger several times to step through the code, and the value changes as I expect within the function, but even when it sets the OnClientClick property to "", the box still pops up when the button is clicked. Is the value not being passed to the client somehow? Any suggestions would be appreciated. Thanks in advance!

You need to add the OnClientClick to the Attributes collection of the button, like this:
btnNext.Attributes.Add("OnClientClick", "YourJavaScriptFunction();");

I have found a solution for my issue. I left the function above as is, but I basically copied the if-else into my page_load event inside if(IsPostBack).

Related

Import checked status from a function

I'm trying to make this code work:
<asp:CheckBox ID="statusChk" runat="server" Visible="true" Enabled="false" Checked='<%# status("de_cancel") %>'></asp:CheckBox>
What i'm trying to do is to retrieve the answer from the status function (which returns bool when i give a string) that i created in the c# source.
Doesn't give me compile error, but doesn't work. Edit: And btw, this is inside in a GridView
This works:
<asp:Label ID="lblInfo" runat="server" Visible="true" Text='<%# Bind("de_cancel") %>'></asp:Label>
But this is NOT what I'm looking for.
Sorry about my bad English.
I'm assuming that this is in a grid view, or some other repeater.
In that case, try this:
<asp:Label ID="lblInfo" runat="server" Visible="true" Text='<%# status(Eval("de_cancel")) %>'></asp:Label>
this is essentially calling your status() method and passing in the value of de_cancel
You may have to convert de_cancel inside your status method though as Eval returns an object.
Just do this in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
//Get your string variable and use it as input here
statusChk.Checked = status("de_cancel");
}
protected bool status(string strStatus)
{
if (strStatus == "de_cancel")
{
return true;
}
else
{
return false;
}
}
This will occur when the page loads. There are other event handlers you may want to use - see http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx
Here is an example of how an event handler (OnSelectedIndexChanged) can be used to set a checkbox when a drop-down value is changed. As the accepted answer points out, you will need to set the AutoPostBack="true" option on the control if you want the event handler method to fire (and the page to refresh) when a control is changed:
Getting a dropdownlist to check a checkbox in asp.net/C#
Also, just looking at your code it looks like you might be using databinding, e.g. with a Repeater or ListView. In this case, please the examples for the ItemDataBound event handler below:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound(v=vs.110).aspx
http://www.codeguru.com/csharp/.net/net_asp/tutorials/article.php/c12065/ASPNET-Tip-Use-the-ItemDataBound-Event-of-a-Repeater.htm
Thanks to Darren tip, i was able to do it. Here what i did to make it work:
<asp:CheckBox ID="statusChk" runat="server" Visible="true" Enabled="false" Checked='<%#status(Convert.ToString(Eval("de_cancel")))%>'></asp:CheckBox>
Thanks everyone. ;)

asp:Button not displaying correctly

this is my scenario:
I want to display a button(btnGenerate) based on the amount of rows displayed in my gridview. I've gotten it to display for a second then it goes away again. I'm using the onclientclick of one of my other buttons(btnImport). What I think is causing the problem is that on the same button(btnImport)'s OnClick event two gridview's performs for each a databind. Could this be the problem? I have written a script using javascript to perform this task from the client side. Is there a better way to do it? What can I do to fix my problem?
Here is my code that I have so far:
<asp:Button runat="server" ID="btnImport" Text="Load Data from File"
BackColor="#990000" ForeColor="White" nowrap OnClick="btnImport_Click"
style="display:none" OnClientClick="DisplayButtonGenerate()"/>
<asp:Button ID="btnGenerate" runat="server" Text="Generate New Stock Codes"
BackColor="#990000" ForeColor="White" OnClick="btnGenerate_Click"
style="display:none" />
I have two gridviews : ErrorsGrid that displays all the faulty records and InventoryGrid that displays the records that are correct. Like I said above, the idea is to display btnGenerate if ErrorsGrid has rowCount=0.
protected void btnImport_Click(object sender, EventArgs e)
{
InventoryGrid.DataBind();
ErrorsGrid.DataBind();
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
FinalMessage.AppendLine(_InsertWrapper.PostData());
}
Here is the script:
<script language="javascript" type="text/javascript">
function DisplayButtonGenerate() {
var rowCount = <%=ErrorsGrid.Rows.Count %>;
var buttonGen = document.getElementById("<%=btnGenerate.ClientID%>");
if(rowCount == 0)
{
buttonGen.style.display = "block";
}
}
</script>
Your btnImport has server-side OnClient and client-side OnClientClick both set. I guess what's happening is the client-side is called first, shows the button, then the server-side one kicks in, the page gets refreshed from the server, and your button is hidden again. You can do it in one way or another, but not both:
Server-side: Remove the OnClientClick & style="display:none" & JavaScript, set the Visible property of the button to false, and in the code-behind click event on the server add:
if(ErrorsGrid.Rows.Count == 0)
btnImport.Visible = True;
Client-side: Return false from the JavaScript function to the OnClientClick:
OnClientClick="return DisplayButtonGenerate()"
function DisplayButtonGenerate() {
....
return false;
}
If you want to update InventoryGrid,ErrorsGrid grid controls in code after you click a button, you need to keep those in a UpdatePanel
<asp:UpdatePanel ID="upnl" runat="server" UpdateMode="Conditional">
<contenttemplate>
InventoryGrid,ErrorsGrid mark up
</contentTemplate>
<Triggers>
//set async trigger as btnImport
</Triggers>
</asp:UpdatePanel>
Let's breakdown your problem into steps.
you click on btnImport, it first calls the OnClientClick, does client side processing
and then does a full postback, goes to server side and processes its server side handler OnClick.
after the OnClick handler is processed, the page again renders, the unconditioned code in the btnGenerate display:none again runs, and the default state is again rendered.
you see the problem? even if you are manipulating certain logic in your clientClick, it all resets on page reload, because your btnImport is doing that.
Solutions:
there are couple of things I can suggest.
Use UpdatePanel to prevent Postback of the entire page or
make your btnImport a client side button altogether, and do a post using xhr or jQuery's ajax.
Set the visibility of btnGenerate on the server side itself
most simple would be the 3rd one i.e. remove the onclientclick event from the code and change your btnImport to do this:
protected void btnImport_Click(object sender, EventArgs e)
{
InventoryGrid.DataBind();
ErrorsGrid.DataBind();
//set visibility of btnGenerate in Page_Load also;
btnGenerate.Visible = ErrorsGrid.Rows.Count == 0;
}
and remove display:none from btnGenerate from client
There's no need for a JS function here.
Simply check the datasource for ErrorsGrid if count != 0 and if it's not just set the visibility of your button in codebehind.
If i've understood your req. correctly, setting 'Visbible' property of button to true or false should work. i.e btnGenerate.Visible=true/false. Initially you can set the button visibility as false then based on the record count you can modify it in the required event handler.

How can I identify, in an ASP.NET Page_Load event, what RadButton initiated a postback?

In my ASP.NET page's Page_Load I'm trying to determine whether a certain button has been clicked and is attempting a postback:
if (Page.IsPostBack)
{
if (Request.Params.Get("__EVENTARGUMENT") == "doStuff")
doSomething();
}
doStuff is a JavaScript within the markup, but I don't want this alone to trigger the doSomething() method call, I also need to be able to ensure that the button the user has clicked is correct.
How can I identify and reference the button control from the code behind once the user clicks? I searched for and discovered this but when I try to implement it, the control returned is always null.
Or use the CommandName and command events.
<telerik:RadButton ID="RadButton1" runat="server" CommandName="first" CommandArgument="one" OnCommand="CommandHandler" />
<telerik:RadButton ID="RadButton2" runat="server" CommandName="second" CommandArgument="two" OnCommand="CommandHandler" />
<asp:Label ID="Label1" Text="" runat="server" />
<asp:Label ID="Label2" Text="" runat="server" />
protected void CommandHandler(object sender, CommandEventArgs e)
{
Label1.Text = e.CommandArgument.ToString();
Label2.Text = e.CommandName;
}
You haven't really explained what you're trying to do, but it sounds like you would have a much easier time if you added an OnClick event handler to the button instead of trying to figure it out in Page_Load. The event handler would only be executed when that button is clicked.

Why can't get the right value of dropdownlist in asp.net

I have following codes in asp.net:
<asp:dropdownlist id="ddlApp" runat="server" />
<asp:button id="btnSmt" runat="server" Text="Submit" />
and code behind:
private void btnSmt_Click(object sender, System.EventArgs e)
{
lbl.Text = ddlApp.SelectedItem.Value;
}
The logic is very simple. Get the selected value of dropdownlist and pass it to lbl.text.
But the problem is no matter how I try, the text show the fist value of list in the dropdownlist rather than the selected value.
And I notice that everytime I click the button the page refresh.
Please help.
BTW, I have the following event binding:
private void InitializeComponent()
{
this.btnSmt.Click += new System.EventHandler(this.btnSmt_Click);
this.Load += new System.EventHandler(this.Page_Load);
this.ddlApp.SelectedIndexChanged +=new System.EventHandler(this.ddlApp_Change);
}
You have to do the binding for the dropdownlist in
if (!Page.IsPostBack)
Else it will re-build the items for the dropdown list on every postback and
therefore only return the currently selected item in the new collection - which is the first.
It also looks like you're missing the btnSmt_Click on the button - but you've probably set it somewhere else...
First of did you debug this??? Cause the C# code seems corrent.
Try changing this:
<asp:button id="btnSmt" runat="server" Text="Submit" />
To
<asp:button id="btnSmt" runat="server" Text="Submit" OnClick="btnSmt_Click" />
if this truely is your code your click event would never have been caught, therefor if you would put a breakpoint in your C# code you would have seen that the action is not triggered.
Anyway, hope it helps

ASP.net checkbox always checked

<asp:CheckBox ID="isSubscribed" runat="server" /> Subscribe to mailing list?<br /><br />
<asp:Button runat="server" CssClass="btn" ID="btnPrefUpdate" OnClick="updatePrefs" Text="Update" /><br /><br />
This fires in the code behind:
protected void updatePrefs(object sender, EventArgs e)
{
Response.Write(isSubscribed.Checked);
Response.End();
}
But it's always coming out as true! Whether it is checked or not! I know I'm doing it wrong, could someone show me how to access this value properly?
like #Curt said, it looks to me like you have something in your page_load. if you set the value in Page_Load make sure it is inside the following if statement
if(!Page.isPostBack)
{
isSubscribed.Checked = true;
}
You are doing it the right way. The boolean property Checked should just say True or False (I even tested it). Is your Page_Load doing something with the checkbox? In other words, is the value of the checkbox somehow (re)set when the post back is occuring (the postback of the button click).
In your Page_Load method you could include:
if (!this.IsPostBack)
{
// Set default or loaded values for controls
}

Categories

Resources