Why does the button event handler not work in C#? - c#

In the HTML section, I created an "addClub" button, whenever it is clicked, two textboxes appear along with a new submit button. I created the submit button in the addClub_click method in the .cs file, however, the event handler of the submit button is not working. I tried several codes and no one is working.
Here is my code that I have created in the .cs file:
protected void AddClub_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
clubname = new TextBox();
Label cn = new Label();
cn.Text = "Club Name ";
PlaceHolder1.Controls.Add(cn);
PlaceHolder1.Controls.Add(clubname);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
clublocation = new TextBox();
Label cl = new Label();
cl.Text = "Club Location ";
PlaceHolder1.Controls.Add(cl);
PlaceHolder1.Controls.Add(clublocation);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Button Submit = new Button();
Submit.Click += new EventHandler(Submit_Click);
Submit.Text = "Add";
PlaceHolder1.Controls.Add(Submit);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
protected void Submit_Click(object sender, EventArgs e)
{
Response.Write("Completed successfully");
}
Edit
I performed several other trials and I kind of discovered where is the problem. Whenever I move the code of the Submit button to the page_load section, the eventhandler works; thus the problem is in creating the button and adding to it the eventhandler within the addClub_click method. However I couldn't find a solution to that. Does anyone know how to perform that?

replace
Submit.Click += new EventHandler(Submit_Click);
with
Submit.Click += Submit_Click;

I think you need to back up the truck here somewhat.
You looking and thinking of this as a user interface problem, when in fact this is "more" of a data problem.
I mean, after you add that "row" of data, then what?
Do you plan THEN to somehow grab, get, gather that information and save it into a database? or when you leave the page, all data is gone?
And WHY oh why would you try to write code in a page for repeating data?
One of the "greatest" strengths of webforms is its ability to repeat data, and do so WITHOUT even having to write loops!
You need/want to think of this problem as a data management problem.
In 99 out of a 100 problems?
If you writing code to inject controls into a page, YOU DOING IT WRONG! You just are!!
I mean, after you inject all those controls, how you going to come back and edit that data? Too much pain.
I mean, after you inject all those controls, how you going to come back and even simple display that data? Too much pain!
Don't, just don't go down this road, it is the WRONG road, and wrong approach. You will forever more be attempting to maintain this code, not able to re-use that code for editing "existing" data, and at the end of the day, you will have achieved some working code of VERY LITTLE value.
Webforms is "bristling" with boatloads of controls that will do this dirty work of repeating data for you. webforms has a whole bunch of controls that will do all this work for you, but BETTER means it can also display the data. In in 09 out 10 cases:
You don't have to write loops for such code.
You don't have to try and write code to inject controls
You have all kinds of fantastic built in events to do heavy lifting for you.
Such controls are "data aware", and you reduce both markup you have to write, and code.
Be it a repeater, listview, girdview and more?
Let the asp.net system do all this dirty work for you.
Let the poor saps writing PHP or using mvc write all that silly looping code in their markup, and create world poverty while they are at this.
And MORE important, for the "same" amount of work, you write less code, and that code gives you full data base operations.
Lets do an example:
Lets toss some text boxes - say some to enter hotel infomration.
Then lets add a "save" button, send the one row to a data base, and then display the results (in a grid view).
So, we have this:
<h3>Add Hotels</h3>
<div id="EditRecord" runat="server" style="float: left;padding: 15px; border:solid">
<div style="float: left" class="iForm">
<label>HotelName</label>
<asp:TextBox ID="txtHotel" runat="server" Width="280" f="HotelName" /><br />
<label>First Name</label>
<asp:TextBox ID="tFN" runat="server" Width="140" f="FirstName"/><br />
<label>Last Name</label>
<asp:TextBox ID="tLN" runat="server" Width="140" f="LastName" /><br />
<label>City</label>
<asp:TextBox ID="tCity" runat="server" Width="140" f="City" /><br />
</div>
<div style="float: left; margin-left: 20px" class="iForm">
<label>Description</label>
<br />
<asp:TextBox ID="txtNotes" runat="server" Width="400" TextMode="MultiLine"
Height="150px" f="Description"></asp:TextBox><br />
</div>
<div style="clear: both"></div>
<button id="cmdSave" runat="server" class="btn myshadow" type="button"
onserverclick="cmdSave_Click">
<span aria-hidden="true" class="glyphicon glyphicon-floppy-saved">Save</span>
</button>
</div>
So far, really drag + drop in the desinger.
So, our code to load (when we come back to edit the data)
is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
string strSQL = "SELECT * FROM tblHotelsE ORDER BY HotelName";
DataTable rstData = General.MyRst(strSQL);
GridView1.DataSource = rstData;
GridView1.DataBind();
ViewState["PKID"] = 0;
}
And that save/add button code is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
int PKID = (int)ViewState["PKID"];
General.FWriter(this.EditRecord, PKID, "tblHotelsE");
General.FClear(this.EditRecord);
LoadData(); // re-load grid to show any changes
}
And our edit the data again button is this:
protected void cmdEdit_Click(object sender, EventArgs e)
{
HtmlButton btn = sender as HtmlButton;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
ViewState["PKID"] = PKID;
string strSQL = $"SELECT * FROM tblHotelsE WHERE ID = {PKID}";
DataRow rstData = General.MyRst(strSQL).Rows[0];
General.FLoader(this.EditRecord, rstData);
}
So, no "injecting" of controls is required.
The end result looks like this:
Note carefull.
We can add 1 or 20 rows - we DO NOT have to write code to create controls, inject controls.
Now, I can post some of the helper routines (floader, fwriter). That does does loop the controls, and load from/to the database, but at the end of the day?
don't try and inject controls for repeating data - it simply not the way how webforms works.
Do things the web forms way, and you wind up with less effort, less code, and not have to write code to inject controls to display repeating data.

Related

add multiple innerhtml in asp.net

my x.aspx file :-
<form id ="Content3ret" runat="server">
</form>
<asp:Button ID="Button1" runat="server" OnClick ="Button1_Click"/>
my x.aspx.cs file :-
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
Content3ret.innerhtml = "<table id = '"+x+"'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
}
what I am trying to do is :-
when I click button each and every time there should be new radio button added with other .
like 3 button click I need 3 radio button .
but with this code when I click only one radio button creating .
like 3 click only one radio button with new id.
can anyone help me ?
When you add data on Content3ret.innerhtml and render them on the pages, this data are lost / gone / stay on page and never come back on post back - because this inner html is not post back with the second click on button.
So you have to render them on page, and at the same time saved it somewhere - preferable on viewstate because of asp.net
so the page will be like
<form id="form1" runat="server">
<div runat="server" id="divPlaceOnme"></div>
<asp:Button ID="Button1" runat="server" Text="ok" OnClick ="Button1_Click"/>
</form>
and on code behind we have
const string InnerHtmlKeeper_name = "InnerHtmlKeeper_cnst";
string InnerHtmlKeeper
{
get
{
var RetMe = ViewState[InnerHtmlKeeper_name] as string;
if (string.IsNullOrEmpty(RetMe))
return string.Empty;
else
return RetMe;
}
set
{
ViewState[InnerHtmlKeeper_name] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var x = Guid.NewGuid().ToString();
// we keep the new with the previous data on this ViewState
InnerHtmlKeeper += "<table id = '" + x + "'> <tr> <td><input type='radio' name='radiotest' checked='checked'/></td> </tr> </table>";
// we add the final render on the div on page
divPlaceOnme.InnerHtml = InnerHtmlKeeper;
}
Last words.
Your approaches have many issues - and your code not working as it is. The button must be on the form, and you have to render inside some other div.
The point here is to show you have to save some actions on viewstate - beside that for a good solution on your problem you must use some javascript to render the radio without post back.

Calculating score on a quiz test using asp.net C# with database

I'm trying to create a quiz in web application in asp.net C# using a database. The quiz has 25 question and 5 answers and each answer has a number of points(totally agree(1),agree(2), not sure(3), disagree(4), totally disagree(5)).
The questions and answers are in a database.
What I want is when i click on the submit button to calculate the score from those questions and put the score in a table from my database.
I try to do a if (radiobutton1.checked){
score=2}
but it doesn't work because of the repeater...I guess i'm not sure.
I try to delete the repeater but when i done that the questions and answers do not display on the web page.
In my aspx file i write code to display my data from database like that(using a repeater and table):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td> <%#Eval("IDq") %> ) <%#Eval("qustion") %></td></tr>
<tr>
<td>
<asp:RadioButton ID="RadioButton1" runat="server" Text='<%#Eval("ans1")%>' GroupName="quiz" Value="1"></asp:RadioButton>
<asp:RadioButton ID="RadioButton2" runat="server" Text='<%#Eval("ans2") %>' GroupName="quiz" Value="2"></asp:RadioButton>
<asp:RadioButton ID="RadioButton3" runat="server" Text='<%#Eval("an3") %>' GroupName="quiz" Value="3"></asp:RadioButton>
<asp:RadioButton ID="RadioButton4" runat="server" Text='<%#Eval("ans4") %>' GroupName="quiz" Value="4"></asp:RadioButton>
<asp:RadioButton ID="RadioButton5" runat="server" Text='<%#Eval("ans5") %>' GroupName="quiz" Value="5"></asp:RadioButton>
<br />
</td>
</tr> </table>
</ItemTemplate></asp:Repeater>
Ok, you have a good start.
And I am going to suggest that in place of the RadioGroup tag?
That DOES get you automatic ONLY one choice. The problem is we STILL will have to check all 5 controls.
A better control in this case to use what is called a RadioButtonList. It works VERY much like having used RadioGroup, but the REALLY nice part?
It is ONE control, and if there are 3 or 15 choices for Radio button group, it as ONE control returns
the index of the selection (0 to N)
the text value of the selection
the value value of the selection.
So I recommend using a RadioButton list - since it is "one thing" that returns the selections.
The "major" problem with the RadioButtonList is you CAN'T use those cool data bound expresisons ike you are using now (that was a good call/design on your part).
However, either we write a loop to "get/check" the 5 raido buttons, or we write a loop to fill the Radiobutton list - I think using code to fill out the RadioButton list is a better choice.
Also, you new - and I see you are attempting to use some "table and "tr" to help you lay out things. You don't really need this.
Now, because ALL of the above ideas saves us so much time, so much code? Well, then we can add extra code to say
show the score and results after we submit
tell the user they did NOT answer a question - they MUST!!!
heck, toss is a cool check box, or X box to show wrong or right.
Allow a question to only have say 2 answers - not always all 5
Ok first up, our table - it looks like this:
So, we have the IDq (id of question). The 1 to 5 possible answers, and then a column with the CORRECT answer.
Ok, now our markup. As I stated, since we reduced so much markup and code, then I added the message in big bold red that appears when a user did not answer all questions.
And I also added a "results" box that shows when you hit submit (number wrong, and correct).
So, now our Markup becomes like this:
<div style="width:35%">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="float:left">
<asp:Label ID="Question" runat="server"
Text = '<%# Eval("IDq").ToString + " ) " + Eval("question") %>'
Font-Size="X-Large">
</asp:Label>
</div>
<div style="float:right">
<img id="MyImage" runat="server" src="" height="48" width="48" />
</div>
<div style="clear:both">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" ></asp:RadioButtonList>
</div>
<br />
<hr></hr>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="cmdDone" runat="server" Text="Submit" />
<div id="MyError" style="display:none;normal;color:red" runat="server">
<h2>You have not answered all questions</h2>
<h2>Please answer all questions before submitting</h2>
</div>
<div id="Results" runat="server" style="clear:both; display:none" >
<h2>Results</h2>
<asp:TextBox ID="MyCorrect" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="InCorrect" runat="server"></asp:TextBox>
</div>
</div>
so, not a lot of markup - and we added quite a bit new features.
I also tossed in the idea to show a check box for correct, and wrong - you can remove that part - but it does help you learn a lot here.
So, now when I run the code, I see this:
So note the questions I have correct. As I stated - you may well want to remove that.
And note the message that I not yet answered all questions.
So, as noted, we have a LITTLE bit more code to load up the Repeater, but less to check things after.
So, our code now looks like this:
private DataTable MyTable = new DataTable();
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
LoadData();
ViewState["MyTable"] = MyTable;
}
else
MyTable = ViewState["MyTable"];
}
public void LoadData()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from tblQuestions ORDER BY IDq",
new SqlConnection(My.Settings.TEST4)))
{
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
Repeater1.DataSource = MyTable;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRow MyRow = MyTable.Rows(e.Item.ItemIndex);
RadioButtonList rBtnList = e.Item.FindControl("RadioButtonList1");
for (var i = 1; i <= 5; i++)
{
var strR = "ans" + i;
if (IsDBNull(MyRow(strR)) == false)
{
ListItem nItem = new ListItem(MyRow(strR), i);
rBtnList.Items.Add(nItem);
}
}
}
}
protected void cmdDone_Click(object sender, EventArgs e)
{
// check all rows - make sure all have a answer
// show check box for correct answers
// total up correct answers (count)
// total up wrong answers (count)
MyError.Style("Display") = "none";
int Correct = 0;
int Wrong = 0;
int NotAnser = 0;
foreach (RepeaterItem ritem in Repeater1.Items)
{
RadioButtonList RadioBut = ritem.FindControl("RadioButtonList1");
if (RadioBut.SelectedIndex >= 0)
{
HtmlImage MyImage = ritem.FindControl("MyImage");
if (MyTable.Rows(ritem.ItemIndex).Item("Answer") == RadioBut.SelectedIndex + 1)
{
Correct += 1;
MyImage.Src = "/Content/ok.png";
}
else
{
Wrong += 1;
MyImage.Src = "/Content/reject.png";
}
}
else
{
NotAnser += 1;
}
}
// if missed questions then display warning.
if (NotAnser > 0)
MyError.Style("Display") = "normal";
else
{
MyCorrect.Text = "Correct answers = " + Correct;
InCorrect.Text = "Wrong answers = " + Wrong;
Results.Style("Display") = "normal";
}
}
So you can see in that submit button code, we are NOW with great ease to loop the repeater, get the user answer, check against the table data.
And note the other trick - I persist MyTable into ViewState. I did this since I did not want to have to re-load the table each time - it just means for ANY button click, control and code behind? I ALWAYS have the data table at my fingertips
Now, given the above does total up the answer, then you would have to add 2-5 more lines of code to write out the total, or the results - it not clear if you plan to have some other table where you have say some student ID, or user id, and you save the total results of the test (or the correct count, or wrong count).
so, the final result looks like this:

Can't handle events in ASP.net

I am new to ASP.net. I downloaded one responsive page template from this link. For my convenience I changed this HTML code to asp.net web form(i.e .html to .aspx) I added a button in that page and I generated click event. When I place a breakpoint in the .cs code and when I click this button in the browser the event is not handled. Even I tried with link button and other controls. I wrote some code in page_load event. It works perfectly. How to solve this issue. Any problem with the downloaded template or can't I handle events in such type of layout. Please go through the below code
Even I tried placing outside the html list control. Its not working. Please go through the link for the details of template here
Issue Placed Menu but event is not working. I tried using other control and its working..
<asp:Menu ID="mini" OnMenuItemClick="mini_MenuItemClick" runat="server" Orientation="Horizontal">
<Items> <asp:MenuItem Text="Item">
<asp:MenuItem Text="sdaad" Value="1">
<asp:MenuItem Text="MenuSub1" Value="MenuSub1" ></asp:MenuItem>
<asp:MenuItem Text="MenuSub2" Value="MenuSub2" ></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Item" Value="Item">
<asp:MenuItem Text="MenuSub" Value="MenuSub"></asp:MenuItem>
</asp:MenuItem>
</asp:MenuItem></Items>
</asp:Menu>
I have tried again after download that template and get issue if because of jQuery Validation script, there are three text boxes in bottom so when we are click on our asp.net button then page will first run client side script and client side script will return false so it will not do post-back till validation js will not return true, so to solve asp.net click problem just remove :
<script type="text/javascript" src="js/jqBootstrapValidation.js"></script>
Have you attached ID to your button? Give ID to your Button and try again. As it is server control, it is not so logical to use it without ID... And post your code behind, I need to look at it and then may be I could help you.
One way to check whether the event has been bound to the control, is to go to the design view of the page, select properties for the button, see the section for events and check whether an event has been attached to click. If not double click in the click event section and an event will get attached to your element.
Button.Click event
Why do you want to put that button inside a list control?
Give an ID to your button control.
ID="Button1"
Your Click event should be like this:
protected void Button1_Click(object sender, EventArgs e){
//some code
}
Find and change Categories block to the next:
<div class="categories">
<asp:Button ID="Button1" CssClass="btn btn-primary" runat="server" Text="Button" OnClick="Button1_Click" />
<ul class="cat">
<li>
<ol class="type">
<li>All</li>
<li>Web Design</li>
<li>App Development</li>
<li>Branding</li>
</ol>
</li>
</ul>
<div class="clearfix"></div>
</div>
your ButtonClickListenes is:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script language='javascript'>alert('Button is working');</script>");
}
Your code behind (full version):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
MyFunction();
}
protected void MyFunction()
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-CEUQVES;Initial Catalog=register;Integrated Security=True;Pooling=False");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Admintr where projectid=mba ", con);
DataSet ds = new DataSet();
sda.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
//GridView1.Columns[0].Visible = false;
}
}
protected void Unnamed_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "view")
{
string str = e.CommandArgument.ToString();
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + str + "\"");
Response.TransmitFile(Server.MapPath(str));
Response.End();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<script language='javascript'>alert('Button is working');</script>");
}

adding handler to button code behind

I am rendering some html in code behind using StringBuilder which includes a button. I am also trying to add a handler to this and I think perhaps not surprisingly it does not fire. Can I include an event handler to a button in this way?
sb.Append("<td>");
sb.Append("<input type='button' runat='server' id='butResetPassword' value='Reset Password' onserverclick='butSendEmail_Click' />");
sb.Append("</td>");
User.InnerHtml = sb.ToString();
this is the eventhandler that appears in the same code behind page
protected void butSendEmail_Click(object sender, EventArgs e)
{
labTester.InnerText = "Thanks for clicking me";
}
I answered a similar question of yours recently.
Unless you have a really good reason to generate markup in the code behind, keep it separate, otherwise stick to classic ASP.
You can do:
Markup:
<asp:Button runat="server" id="butResetPassword" OnClick="butSendEmail_Click" />
Code behind:
protected void butSendEmail_Click(object sender, EventArgs e)
{
//Reset the password here
labTester.InnerText = "Thanks for clicking me";
}
Edit* If all you need to do is display that confirmation message and not interact with any data or controls, then you could bind the button to a js function, change onserverclick to onclick:
<input type='button' runat='server' id='butResetPassword' value='Reset Password' onclick='butSendEmail_Click' />
And then have some js to handle this:
<script type="text/javascript">
function butSendEmail_Click() {
alert("Thanks for clicking me");
//Or set the labels text
var elem = document.getElementById("labTester");
elem.InnerHtml = "Thanks for clicking me";
}
</script>

ASP.NET C# - Retrieving HTML Button from Repeater

I have a repeater containing, amongst others, two buttons. One of the buttons is an ASP.NET button whilst the other is of the type "input type="button"".
Now, in my code-behind, I want to retrieve both buttons from the repeater to either hide them or show them. I have successfully hidden the ASP.NET button however I do not know how to retrieve the other button.
Here is some code in ASP.NET:
<input type="button" name="ButtonEditUpdate" runat="server" value="Edit Update" class="ButtonEditUpdate" />
<asp:Button ID="ButtonDeleteUpdate" CssClass="ButtonDeleteUpdate" CommandName="Delete" runat="server" Text="Delete Update" />
Here is the code-behind:
protected void RepeaterUpdates_ItemBinding(object source, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
TextBox Update_ID = (TextBox)item.FindControl("TextBoxUpdateID_Repeater");
//Button Edit_Update = (Button)item.FindControl("ButtonEditUpdate");
Button Delete_Update = (Button)item.FindControl("ButtonDeleteUpdate");
if (Social_ID == String.Empty)
{
//Edit_Update.Visible = false;
Delete_Update.Visible = false;
}
}
How can I retrieve the HTML button and hide it since it is NOT an ASP.NET button?
That button is a HTML control and will be of type System.Web.UI.HtmlControls.HtmlButton
System.Web.UI.HtmlControls.HtmlButton button = item.FindControl("ButtonEditUpdate") as System.Web.UI.HtmlControls.HtmlButton;
if(button!=null)
button.Visible = false;
In general you cannot straightly retrieve a plain-old HTML button because ASP.NET considers that as part of the text markup. Fortunately, you already added runat="server" that makes your button a server control.
The easiest way is to use an HtmlButton control. But in your markup you need the id attribute
<input type="button" name="ButtonEditUpdate" runat="server" value="Edit Update" class="ButtonEditUpdate" id="ButtonEditUpdate" />
Then in the code behind
//Button Edit_Update = (Button)item.FindControl("ButtonEditUpdate");
HtmlButton Delete_Update = (HtmlButton)item.FindControl("ButtonEditUpdate");
If you just want to set the visibility you shouldn't need to cast it.
var myButton = e.Item.FindControl("ButtonEditUpdate");
if(myButton != null)
myButton.Visible = false;
EDIT: you should give your button an ID.

Categories

Resources