How to get Id of clicked input created at runtime - c#

I want to add some submit input to my page at run time and use the Id of the clicked input in an event handler.
Here is my aspx code:
<asp:Content runat="server" ID="CNT1" ContentPlaceHolderID="CPH1">
<div id ="CNT" runat="server">
</div>
</asp:Content>
<script language="c#" runat="server">
private void btnClick(object sender, EventArgs e)
{
string id = ((HtmlInputSubmit) sender).ID;
// some other code using id
}
</script>
and here is my aspx.cs code
foreach (DataRow dr in dt.Rows)
{
CNT.Controls.Add(new LiteralControl(
"<input type=\"submit\" runat=\"server\" id="+dr.ItemArray[0].ToString()+
" value=\"val1\" OnServerClick=\"btnClick\"/>"));
}
I can use this code to create my inputs on the aspx page without any problems.

Change access modifier from private to protected:
protected void btnClick(object sender, EventArgs e)
{
string id = ((HtmlInputSubmit) sender).ID;
// some other code using id
}
Because the private member function can't be accessed.

Related

persist ddl values and selected value in between postbacks

I have a save button and a drop down list on a page. Inside the page Load, the drop down list is populated if !Page.PostBack (AutoPostBack=false). So, the first time I load the page, the drop down list is populated. I also have a save method to go with the save button. When this button is clicked, it should do something with the selected value of the drop down list. My problem is that the drop down list has no value (is null) inside the button save method. How would you fix this?
Markup:
MyClass.aspx
<%# Page Language="C#" AutoEventWireup="true" Inherits="MyClass" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainRegion" runat="server">
<div>
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="myDdlChange" ViewStateMode="Enabled" EnableViewState="true" />
</div>
<br />
<div style="min-width: 300px; max-width: 770px;">
<asp:TextBox id="txtBox" runat="server" TextMode="MultiLine" />
</div>
<div class="buttonContainer">
<span >
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</span>
</div>
</asp:Content>
Then, in the code behind:
MyClass.aspx.cs
public class MyClass
{
protected global::System.Web.UI.WebControls.DropDownList myDdl;
protected global::System.Web.UI.WebControls.TextBox txtBox;
protected global::System.Web.UI.WebControls.Button btnSave;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (this.Page.IsPostBack)
Session["selectedID"] = myDdl.SelectedValue; // my attempt to put the selected value from ddl in a session var, to use it later inside the save method but it didn't work
if (!Page.IsPostBack)
{
//create array1 here
myDdl.Items.Clear();
myDdl.Items.AddRange(array1);
Session["selectedID"] = myDdl.SelectedValue;
myDdlChange(null, null);
this.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
//do something based on myDdl.SelectedValue (which shouldn't be null)
}
protected void myDdlChange(object source, EventArgs e)
{
txtBox.Text = myDdl.SelectedValue;
}
}
}
I think the main problem is you should be using Page_Load instead of OnLoad.
You don't need to use Session to remember the SelectedValue.
Try something like this which works for me...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateDropdown();
}
private void PopulateDropdown()
{
myDdl.Items.Clear();
var array1 = new ListItem[3];
array1[0] = new ListItem("item1", "item1");
array1[1] = new ListItem("item2", "item2");
array1[2] = new ListItem("item3", "item3");
myDdl.Items.AddRange(array1);
myDdl.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
var selectedVal = myDdl.SelectedValue; // putting a breakpoint here shows myDdl.SelectedValue is not null
}
protected void myDdlChange(object sender, EventArgs e)
{
}

Values in dynamically added controls not retained on postback

I have a page with a number of controls of type MyControl added dynamically. The count is stored in the ViewState, and only incremented with a button click.
In MyControl, I have a TextBox control, and a Label control. When the text is changed in the textbox, the value is multiplied by 2 and displayed in the label control.
To do this, I have added an OnTextChanged event and set AutoPostBack to true.
My problem is this: when I have any number of MyControl's on the page, and change the text in any of the textboxes, the label is updated and the values are retained on postback.
However, if I click the increment button on the page, all the values in the textboxes and labels are lost.
My code:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test.Default" EnableViewState="true" %>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
Count:
<asp:Label ID="lblCount" runat="server"></asp:Label>
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="+" />
<asp:Panel ID="pnlControls" runat="server"></asp:Panel>
</form>
</body>
</html>
Default.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int count = 0;
//if not postback, then set count and store in viewstate
if (!Page.IsPostBack)
{
count = 1;
ViewState["count"] = count;
}
LoadControls();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//increment count
ViewState["count"] = (int)ViewState["count"] + 1;
pnlControls.Controls.Clear();
LoadControls();
}
private void LoadControls()
{
//add controls to page
for (int i = 0; i < (int)ViewState["count"]; i++)
{
MyControl con = (MyControl)LoadControl("MyControl.ascx");
con.ID = i.ToString();
pnlControls.Controls.Add(con);
}
//set count label
lblCount.Text = ViewState["count"].ToString();
}
}
MyControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="Test.MyControl" EnableViewState="true" %>
<div>
<asp:TextBox ID="txtField" runat="server" OnTextChanged="txtField_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Label ID="lblAnswer" runat="server" Text="answer:"></asp:Label>
</div>
MyControl.ascx.cs
public partial class MyControl : System.Web.UI.UserControl
{
public string Text;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtField_TextChanged(object sender, EventArgs e)
{
lblAnswer.Text = (int.Parse(txtField.Text) * 2).ToString();
}
}
Am I missing something obvious? How can I keep the values when the button is clicked?
The reason you lose the info of MyControl(s..) is when you click the button you clear them:
pnlControls.Controls.Clear();
If you want to keep the values I recomended you to use Session variables, for example an array when you fire "txtField_TextChanged" to save "lblAnswer.Text", be carefull with the ID's to differentiate from each other in the Session variable.
Finally, I'd put "LoadControls();" inside Page_Load, outside I think It's redundant.

Call code behind method from aspx

I have the following aspx code where I am calling a method from code behind. The result of the code behind method is not getting rendering in the page.
<%# Page Language="C#" AutoEventWireup="false" Src="LeftMenuSrce.aspx.cs" Inherits="LeftMenuSrce" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Home</title>
</head>
<body>
<asp:Table ID ="LeftMenuTable" runat="server">
<asp:TableRow>
<asp:TableCell ID="LeftMenuSrce" OnDataBinding="_getLeftMenuSrc"></asp:TableCell></asp:TableRow>
</asp:Table>
</body>
</html>
Below is my cs code:
public class LeftMenuSrce : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TableCell LeftMenuSrce;
protected System.Web.UI.WebControls.Table LeftMenuTable;
protected void Page_Load(object sender, EventArgs e)
{
LeftMenuSrce.DataBind();
}
protected string _getLeftMenuSrc()
{
string leftMenu;
leftMenu = "LeftMenuNew.aspx";
return leftMenu;
}
}
Even I have tried div instead of asp:tables, but nothing was working.
<div>
<%#_getLeftMenuSrce()%>
</div>
Any clues to overcome this issue? Thanks in advance.
Please note I have referred below links, but nothing helped me.
How to call a code-behind method from aspx page?
Call code behind method from aspx page
ASP.NET - Use variable in .aspx page
Use <%=_getLeftMenuSrc() %>
You must implement your method "_getLeftMenuSrc()" as an event handler.
Example:
protected void _getLeftMenuSrc(object sender, EventArgs e) {}
I guess you simply try to write some text into your TableCell LeftMenuSrce.
One way to do this is writing a OnPreRender event handler like this:
protected void TableCell1_OnPreRender(object sender, EventArgs e)
{
TableCell1.Text = "My text in a cell !!";
// Hint: 'sender' is your table cell ;-)
((TableCell) sender).Text = "My other text in that cell !!";
}
An other way is to fill all your tables cells within the Page_Load event. Like this:
protected void Page_Load(object sender, EventArgs e)
{
TableCell1.Text = "My text in a cell !!";
}
BTW: Don't use tables to build a navigation ;-). Try this link: http://www.w3schools.com/css/css_navbar.asp

How to I carried out Textbox value from ViewState when I postback?

I want to know that how can I trace out the value of Textbox from ViewState.
As user enters any value into Textbox and click submit button because of postback Textbox value disappears ,
But if I used ViewState in this case , then is there any way to see or display that value from Viewstate?
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text += "X";
}
In your page load use this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["Values"] == null)
{
ViewState["Values"] = new string();
}
}
TextBox1.Text = ViewState["Values"].ToString();
}
After that use this.
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Values"] += TextBox1.Text;
}
In the first Page_Load method, You will create a ViewState if its not a postback and its null. After that write the textbox your viewstate, in Button1_Click you will add your new textbox1 to your viewstate.

jquery val() on textbox doesn't set DOM value attribute

I am facing a weird issue and not sure whether it's jquery or combination of my scenario that is causing this. When I set the textbox value using jquery, the textbox displays correct value but the value attribute inside the html is still the one that it was loaded with. Why is it displaying different text then the one in the DOM?
I am having a dynamically generated form which adds two number and displays the addition into third textbox using jquery as shown below.
You can reproduce using below code
The designer file
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".addToTotal").blur(function () {
UpdateTotal();
});
});
function UpdateTotal() {
var add = 0;
$(".addToTotal").each(function () {
add += Number($(this).val());
});
$(".txtTotalPoints").val(add.toFixed(2));
$("#para").text("Sum of all textboxes is : " + add);
}
</script>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<input id="addAll" type="button" value="Sum all Textboxes" /><br />
<p id="para"> </p>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Code behind file that dynamically adds control is
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt1 = new TextBox();
txt1.ID = "txt1";
txt1.CssClass = "addToTotal";
TextBox txt2 = new TextBox();
txt2.ID = "txt2";
txt2.CssClass = "addToTotal";
TextBox txt3 = new TextBox();
txt3.ID = "txt3";
txt3.CssClass = "txtTotalPoints";
PlaceHolder1.Controls.Add(txt1);
PlaceHolder1.Controls.Add(txt2);
PlaceHolder1.Controls.Add(txt3);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
UpdateTextBoxTextProperty(this);
}
}
private void UpdateTextBoxTextProperty(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c is TextBox)
{
string Id = c.ID;
string fieldName = Id.Substring(3);
(c as TextBox).Text = fieldName;
}
if (c.Controls.Count > 0)
{
UpdateTextBoxTextProperty(c);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
you can also user
$(selector).attr("value","Hello World.");
that's what should happen: the dom is dynamic, but when you view the page source, the browser will show the original html. (of course, this depends on which browser you're using, each browser is different)

Categories