Dynamic created radio buttons wont execute event on click - c#

I have a button named "Add Radio Button" in my form, and a text box named TexBox1.
I've written code that when I click the "Add Radio Button", it generates a Radio button; it's own name:
c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Counter"] = 0;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= Convert.ToInt32(ViewState["Counter"]); i++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
RadioButton rb = new RadioButton();
rb.ID = i.ToString();
rb.Text = "Button" + i.ToString();
rb.GroupName = "RB";
rb.CheckedChanged += radioButton_CheckedChanged;
div.Controls.Add(rb);
Panel1.Controls.Add(div);
}
ViewState["Counter"] = Convert.ToInt32(ViewState["Counter"]) + 1;
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = sender as RadioButton;
TextBox1.Text = btn.Text;
}
}
ASP
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add RadioButton" />
</div>
</form>
</body>
</html>
The problem is that after several radio buttons being created, I want the program to work as if each of them is checked, the TextBox1.Text gets the radio button's text string (the name of button) but the function radioButton_CheckedChanged doesn't execute.

You missed this I think
rb.CheckedChanged +=new EventHandler(rb_CheckedChanged);
Check my comments below also

you should set as true to Autopostback property
rb.AutoPostBack = true;

this is how its should be imo:
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= Convert.ToInt32(ViewState["Counter"]); i++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
RadioButton rb = new RadioButton();
rb.ID = i.ToString();
rb.Text = "Button" + i.ToString();
rb.GroupName = "RB";
rb.CheckedChanged += +=new EventHandler(radioButton_CheckedChanged);
div.Controls.Add(rb);
Panel1.Controls.Add(div);
}
ViewState["Counter"] = Convert.ToInt32(ViewState["Counter"]) + 1;
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = sender as RadioButton;
TextBox1.Text = btn.Text;
}

Related

Dynamically create TextBoxes, adding an extra one each time the user clicks a button

I am trying to dynamically create TextBoxes in ASP.NET, my code isn't working the way I expect it to...
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public int TextBoxCount
{
get
{
if (ViewState["tbCount"] == null)
{
ViewState["tbCount"] = 0;
}
return Convert.ToInt32(ViewState["tbCount"]);
}
set
{
int viewState = TextBoxCount;
if (Int32.TryParse(value.ToString(), out viewState))
{
ViewState["tbCount"] = value;
}
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (TextBoxCount == 0)
{
AddTextBox();
}
else
{
RecreateTextBoxes();
}
}
private void AddTextBox()
{
TextBox tb = new TextBox();
tb.ID = "tb" + TextBoxCount++;
Panel1.Controls.Add(tb);
}
private void RecreateTextBoxes()
{
for (int i = 0; i < TextBoxCount; i++)
{
TextBox tb = new TextBox();
tb.ID = "tb" + i;
Panel1.Controls.Add(tb);
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
AddTextBox();
}
protected void btnDisplayText_Click(object sender, EventArgs e)
{
for (int i = 0; i < TextBoxCount; i++)
{
TextBox tb = (TextBox)Page.FindControl("Panel1").FindControl("tb" + i);
if (tb != null)
{
lblText.Text += "," + tb.Text;
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblText" runat="server" />
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
<asp:Button ID="btnDisplayText" runat="server" Text="Display Text" onclick="btnDisplayText_Click" />
<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
</form>
</body>
</html>
What I am trying to do is dynamically create a new TextBox each time the user clicks the btnAdd button. The btnDisplayText button should then concatenate all of the text in each TextBox and display it in lblText.
Thanks for your help!
Use
TextBox tb = (TextBox)Panel1.FindControl("tb" + i);
instead of
TextBox tb = (TextBox)Page.FindControl("Panel1").FindControl("tb" + i);
in btnDisplayText_Click.
Also, remove all code except ViewState["tbCount"] = value; from TextBoxCount setter.
Update:
ViewState is not available in Page_Init. Move your Page_Init code to Page_Load.
int TextBoxID=0;
TextBox textBox = new TextBox();
TextBox.ID="TextBox"+TextBoxID.ToString();
btnDisplayText.Text +=textBox.Text;
lblText.Text=btnDisplayText.Text;
TextBoxID++;

How Can I retrieve data from TextBox, when it's dynamically added by button?

I'm new to coding, hope some can help me a bit, I got stuck at retrieving data from my Dynamically added Text boxes in ASP.NET.
I Master Site and a Content site. I have added some buttons to the content site there are adding or removing the textboxes, after what's needed by the user.
My problem is, that i'm not sure how to retrieve the data correct. hope some body can help me on the way.
My Content site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Her Kan de oprette alt det udstyr der skal sendes til reperation hos zenitel.
</p>
</div>
<div id="div_insert_devices" runat="server">
</div>
// 3 buttons one who add, one who remove textboxes and a submit button
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["DeviceCount"] = ViewState["DeviceCount"] == null ? 1 : ViewState["DeviceCount"];
InsertLine();
}
}
private void InsertLine()
{
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
LiteralControl text = new LiteralControl("<div class=\"divPerDevice\">");
div_insert_devices.Controls.Add(text);
TextBox txtbox = new TextBox();
txtbox.ID = "serial" + i;
txtbox.CssClass = "textbox1";
txtbox.Attributes.Add("runat", "Server");
div_insert_devices.Controls.Add(txtbox);
text = new LiteralControl("</div>");
div_insert_devices.Controls.Add(text);
}
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count++;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnRemoveRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count--;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
}
}
((TextBox)div_insert_devices.FindControl("txtboxname")).Text
Try this one
you can use the following code
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
TextBox txtbx= (TextBox)div_insert_devices.FindControl("serial" + i);
if(txtbx!=null)
{
var value= txtbx.Text;
}
}
}
The way i would attempt this is like the following:
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (Control control in div_insert_devices.Controls){
if (control.GetType() == typeof(textbox)){
Textbox myDynTextbox = (Textbox)control;
Var myString = myDynTextbox.Text;
Please note this code can be simplyfied further but, i have written it this was so you understand how it would work, and my advise would be to store all the strings in a collection of Strings, making it easier to maintain.
}
}
}
Kush
Why don't you use javascript to save the value of textbox. just hold the value in some hidden field and bind it everytime when you need it.
Hi I found the solution after some time here... I did not got any of examples to work that you have provided. sorry.
But I almost started from scratch and got this to work precis as I wanted :)
My Content Site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Some TEXT
</p>
</div>
</div>
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />--%>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:PlaceHolder runat="server" id="DynamicDevices"></asp:PlaceHolder>
<asp:Button id="btnAddTextBox" runat="server" text="Tilføj" CssClass="butten1" OnClick="btnAddTextBox_Click" />
<asp:Button id="btnRemoveTextBox" runat="server" text="Fjern" CssClass="butten1" OnClick="btnRemoveTextBox_Click" />
<asp:Button runat="server" id="Submit" text="Submit" CssClass="butten1" OnClick="Submit_Click" />
<br /><asp:Label runat="server" id="MyLabel"></asp:Label>
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
static int myCount = 1;
private TextBox[] dynamicTextBoxes;
private TextBox[] Serial_arr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myCount = 1;
}
}
protected void Page_Init(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAddTextBox")
{
myCount = myCount >= 30 ? 30 : myCount + 1;
}
if (myControl.ID.ToString() == "btnRemoveTextBox")
{
myCount = myCount <= 1 ? 1 : myCount - 1;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dynamicTextBoxes = new TextBox[myCount];
Serial_arr = new TextBox[myCount];
int i;
for (i = 0; i < myCount; i += 1)
{
LiteralControl literalBreak = new LiteralControl("<div>");
DynamicDevices.Controls.Add(literalBreak);
TextBox Serial = new TextBox();
Serial.ID = "txtSerial" + i.ToString();
Serial.CssClass = "";
DynamicDevices.Controls.Add(Serial);
Serial_arr[i] = Serial;
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
DynamicDevices.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
literalBreak = new LiteralControl("</div>");
DynamicDevices.Controls.Add(literalBreak);
}
}
public static Control GetPostBackControl(Page thePage)
{
Control mycontrol = null;
string ctrlname = thePage.Request.Params.Get("_EVENTTARGET");
if (((ctrlname != null) & (ctrlname != string.Empty)))
{
mycontrol = thePage.FindControl(ctrlname);
}
else
{
foreach (string item in thePage.Request.Form)
{
Control c = thePage.FindControl(item);
if (((c) is System.Web.UI.WebControls.Button))
{
mycontrol = c;
}
}
}
return mycontrol;
}
protected void Submit_Click(object sender, EventArgs e)
{
int deviceCount = Serial_arr.Count();
DataSet ds = new DataSet();
ds.Tables.Add("Devices");
ds.Tables["Devices"].Columns.Add("Serial", System.Type.GetType("System.String"));
ds.Tables["Devices"].Columns.Add("text", System.Type.GetType("System.String"));
for (int x = 0; x < deviceCount; x++)
{
DataRow dr = ds.Tables["Devices"].NewRow();
dr["Serial"] = Serial_arr[x].Text.ToString();
dr["text"] = dynamicTextBoxes[x].Text.ToString();
ds.Tables["Devices"].Rows.Add(dr);
}
//MyLabel.Text = "der er " + deviceCount +" Devices<br />";
//foreach (TextBox tb in Serial_arr)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
//MyLabel.Text += "<br />";
//foreach (TextBox tb in dynamicTextBoxes)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
}
protected void btnRemoveTextBox_Click(object sender, EventArgs e)
{
}
}
Thanks For all the help anyway :)
Hope somebody can use this.
Best regards Kasper :)

How do you add a Gridview programmatically to an UpdatePanel

I can't figure out how to programmatically add a GridView with buttons to an UpdatePanel.
I can do it with simple controls such as buttons and labels, but when I try to add a GridView with buttons a full Postback() occurs.
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected override void OnInit(EventArgs e)
{
UpdatePanel up1 = new UpdatePanel();
up1.ID = "UpdatePanel1";
Button button1 = new Button();
button1.ID = "Button1";
button1.Text = "Submit";
button1.Click += new EventHandler(Button_Click);
Label label1 = new Label();
label1.ID = "Label1";
label1.Text = "A full page postback occurred.";
GridView gv1 = new GridView();
//Where the xml gets bonded to the data grind
XmlDataSource xds = new XmlDataSource();
xds.Data = xml;
xds.DataBind();
xds.EnableCaching = false;
gv1.DataSource = xds;
createButton(gv1, up1);
gv1.RowCommand += new GridViewCommandEventHandler(CustomersGridView_RowCommand);
gv1.DataBind();
up1.ChildrenAsTriggers = true;
up1.ContentTemplateContainer.Controls.Add(button1);
up1.ContentTemplateContainer.Controls.Add(label1);
up1.ContentTemplateContainer.Controls.Add(gv1);
Page.Form.Controls.Add(up1);
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "buttonClicked")
{
int index = Convert.ToInt32(e.CommandArgument);
}
}
void createButton(GridView g)
{
ButtonField tea = new ButtonField();
tea.ButtonType = ButtonType.Image;
tea.ImageUrl = "~/checkdailyinventory.bmp";
tea.CommandName = "buttonClicked";
tea.HeaderText = "space";
g.Columns.Add(tea);
}
protected void Button_Click(object sender, EventArgs e)
{
((Label)Page.FindControl("Label1")).Text = "Panel refreshed at " +
DateTime.Now.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>UpdatePanel Constructor Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:ScriptManager ID="ScriptManager1" runat="server" />
</div>
</form>
</body>
</html>
So how do you add a gridview with buttons programmatically to an UpdatePanel without causing a full PostBack() if the GridView is clicked?
Edit: Other things I have tried
void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
AsyncPostBackTrigger t = new AsyncPostBackTrigger();
t.ControlID = e.Row.Cells[0].ClientID;
t.EventName = "blah";
up1.Triggers.Add(t);
}
Well according to:
And I don't mind having the update panel created at the design time. I just need to be able to add stuff (like tables that contain gridviews that contain buttons into it) programmatically and then be able to do a partial postback
Basically I used your code with small changes:
Removed the binding from the Init event and I execute it in the Load event
The UpdatePanel is created at design time with a nested panel, and you simply add your dynamic controls to that panel
This code will do it (it works on my environment):
ASPX
<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="myPanel">
</asp:Panel>
<br />
<asp:Label runat="server" ID="lblMessage"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Code behind
protected void Page_Init(object sender, EventArgs e)
{
Button button1 = new Button();
button1.ID = "Button1";
button1.Text = "Submit";
button1.Click += new EventHandler(Button_Click);
Label label1 = new Label();
label1.ID = "Label1";
label1.Text = "A full page postback occurred.";
var s1 = Builder<Product>.CreateListOfSize(15).Build();
GridView gv1 = new GridView();
gv1.DataSource = s1;
createButton(gv1);
gv1.RowCommand += new GridViewCommandEventHandler(CustomersGridView_RowCommand);
this.myPanel.Controls.Add(button1);
this.myPanel.Controls.Add(label1);
this.myPanel.Controls.Add(gv1);
}
void createButton(GridView g)
{
ButtonField tea = new ButtonField();
tea.ButtonType = ButtonType.Image;
tea.ImageUrl = "~/checkdailyinventory.bmp";
tea.CommandName = "buttonClicked";
tea.HeaderText = "space";
g.Columns.Add(tea);
}
protected void Button_Click(object sender, EventArgs e)
{
((Label)Page.FindControl("Label1")).Text = "Panel refreshed at " +
DateTime.Now.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
public void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "buttonClicked")
{
//int index = Convert.ToInt32(e.CommandArgument);
this.lblMessage.Text = DateTime.Now.ToString();
}
}
Output
Couldn't you just put the GridView in there at design time and just hide it by setting Visible=false?
If you don't know how many gridviews you need to repeat then you could wrap the GridView in a ListView. The concept is introduced here:
http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html
This might not be the perfect solution I just thought I would offer it seeing as there is a bounty I assume you have hit a brick wall so far.

Can I add buttons in ASP table column and get in which row button was clicked?

I have table with 20 to 30 rows and 3 columns. I would like to add fourth column with buttons or something in the cell that I can click on it. And onClick event I need to get info in which row has happened this click.
Table is generated programmatically on the fly.
Can this be done and I beg for some examples.
EDIT 2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HelpdeskOsControl
{
public partial class Test : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//GenerateTable(getTestData());
}
private List<string> getTestData()
{
List<string> tData = new List<string>();
for (int i = 0; i < 10; i++)
{
tData.Add("proc" + i + "_" + new Random().Next(100) + "_" + new Random().Next(100));
}
return tData;
}
protected void btnClear_Click(object sender, EventArgs e)
{
for (int i = Processes.Rows.Count; i > 1; i--)
{
Processes.Rows.RemoveAt(i - 1);
}
}
protected void btnLoad_Click(object sender, EventArgs e)
{
GenerateTable(getTestData());
}
protected void btnKill_Click(object sender, EventArgs e)
{
lblView.Text = ((Button)sender).ID;
}
private void GenerateTable(List<string> list)
{
int st = 0;
foreach (string line in list)
{
TableRow tr = new TableRow();
Processes.Controls.Add(tr);
foreach(String str in line.Split('_'))
{
int index = tr.Cells.Add(new TableCell());
tr.Cells[index].Text = str;
}
Button b = new Button();
b.Text = "Kill " + st;
b.ID = "btnKill_" + st;
b.Click += new EventHandler(btnKill_Click);
TableCell tc = new TableCell();
tc.Controls.Add(b);
tr.Cells.Add(tc);
tr.TableSection = TableRowSection.TableBody;
Processes.Rows.Add(tr);
st++;
}
Processes.BorderStyle = BorderStyle.Solid;
Processes.GridLines = GridLines.Both;
Processes.BorderWidth = 2;
}
}
}
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Test.ascx.cs" Inherits="HelpdeskOsControl.Test" %>
<asp:Panel ID="Panel1" runat="server" Height="465px" Width="417px">
<asp:Table ID="Processes" runat="server" Height="20px" Width="400px" CssClass="tablesorter">
<asp:TableHeaderRow ID="ProcessesHeader" runat="server"
TableSection="TableHeader">
<asp:TableHeaderCell ID="TableHeaderCell1" runat="server">Name</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell2" runat="server">CPU</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell3" runat="server">Memory</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell4" runat="server"></asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
<asp:Panel ID="Panel2" runat="server">
<asp:Button ID="btnLoad" runat="server" onclick="btnLoad_Click" Text="Load" />
<asp:Button ID="btnClear" runat="server" onclick="btnClear_Click"
Text="Clear" />
<asp:Label ID="lblView" runat="server" Text="Label"></asp:Label>
</asp:Panel>
</asp:Panel>
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HelpdeskOsControl._Default" %>
<%# Register src="Test.ascx" tagname="WebUserControl" tagprefix="Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Test Control</p>
<Test:WebUserControl ID="Test" runat="server" />
</div>
</form>
</body>
</html>
Can please someone checks why this code is NOT working when I comment out GenerateTable(getTestData()); in Page_Load procedure.
If it is a HTMLtable generated in code behind,
assuming this is how your code looks like,
HtmlButton b = new HtmlButton();
b.ClientID = "Button_" + i;
b.Attributes.Add("onClick", "your function(this)");
use the suffix part from the parameter in the method to check which butto has been click.
Hope this helps!!
Edit:
You may still go with the above logic. In the click event of the button ( which appears to be common for all the buttons), you ca use the sender object and get the ID and know which button has been clicked as follows:
protected void KillButton_Click(object sender, EventArgs e)
{
string ID = ((Button)sender).ID;
}
and you may attach the event handler in this fashion:
b.Click += new EventHandler(KillButton_Click);
ClientID is read Only...therefore you cannot have the line that tries to set the clientID

Problems with events in Asp.net

I am completly new in asp.net and I'm having some problems with it.
I created litle web form for demo and learning and I have some problems with it. Hopefuly you can help me :)
What I want is that:
when I click on "Kill X" button in table, I get "You pressed button Kill X" message in label "lblMsg". I Also want that I get table with new data.
when I click "Load" button, I need to get additional rows in the table. For example now when page loads there is 10 rows in table and when I click "Load" I nedd to get additional 10 rows at the end into the same table.
P.S:
I would be grateful for some tutorial how to deal with events in asp.net.
Bellow is the code:
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="HelpdeskOsControl.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="Panel1" runat="server" Height="465px" Width="417px">
<asp:Table ID="Processes" runat="server" Height="20px" Width="400px" CssClass="tablesorter">
<asp:TableHeaderRow ID="ProcessesHeader" runat="server"
TableSection="TableHeader">
<asp:TableHeaderCell ID="TableHeaderCell1" runat="server">Name</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell2" runat="server">CPU</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell3" runat="server">Memory</asp:TableHeaderCell>
<asp:TableHeaderCell ID="TableHeaderCell4" runat="server"></asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
<asp:Panel ID="Panel2" runat="server">
<asp:Button ID="btnLoad" runat="server" onclick="btnLoad_Click" Text="Load" />
<asp:Button ID="btnClear" runat="server" onclick="btnClear_Click"
Text="Clear" />
<asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
</asp:Panel>
</asp:Panel>
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HelpdeskOsControl
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenerateTable(getTestData());
}
private List<string> getTestData()
{
List<string> tData = new List<string>();
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
tData.Add("proc" + i + "_" + rand.Next(100) + "_" + rand.Next(100));
}
return tData;
}
protected void btnClear_Click(object sender, EventArgs e)
{
for (int i = Processes.Rows.Count; i > 1; i--)
{
Processes.Rows.RemoveAt(i - 1);
}
}
protected void btnLoad_Click(object sender, EventArgs e)
{
GenerateTable(getTestData());
}
protected void btnKill_Click(object sender, EventArgs e)
{
lblMsg.Text = "You pressed button " + ((Button)sender).Text;
}
private void GenerateTable(List<string> list)
{
int st = 0;
foreach (string line in list)
{
TableRow tr = new TableRow();
Processes.Controls.Add(tr);
foreach (String str in line.Split('_'))
{
int index = tr.Cells.Add(new TableCell());
tr.Cells[index].Text = str;
}
Button b = new Button();
b.Text = "Kill " + st;
b.ID = "btnKill_" + st;
b.Click += new EventHandler(btnKill_Click);
TableCell tc = new TableCell();
tc.Controls.Add(b);
tr.Cells.Add(tc);
tr.TableSection = TableRowSection.TableBody;
st++;
}
Processes.BorderStyle = BorderStyle.Solid;
Processes.GridLines = GridLines.Both;
Processes.BorderWidth = 2;
}
}
}-
I understand this is your first time with ASP.NET and want to help you learn more about its potentials.
First of all, I would replace the code you wrote with data binding, which is a way to easily build tables without having to write methods like your generateTable. ASP.NET takes care of building the table by itself. It will take me a while to illustrate you full code for achieving this, but I hope you can grab the documentation and start learning with my help.
The key control is GridView. It can be populated using a two-lines code fragment
protected override OnLoad(EventArgs e)
{
if (!IsPostback) DataBind();
}
protected override void OnDataBind(EventArgs e)
{
gridView.DataSource = getTestData();
gridView.DataBind();
}
You must first configure columns in layout. The articles about GridView deal with this, and you can add a button for each row.
Now,
you can set the buttons as command buttons, thus not only raising the Click event, but, more important, the Command event which takes a name and an argument. That's where you can inject your code. For example
<asp:Button id="btnSomething" CommandArgument="[procId]" CommandName="kill" OnCommand="myCommandHandler" />
protected void myCommandHandler(object sender, CommandEventArgs e)
{
if (e.CommandName=="kill")
{
killProcess(e.CommandArgument);
DataBind(); //MOST IMPORTANT
}
}
Hope to have been of help. I wrote this code by hand, so please understand me if it will not work immediately
You need to store the state of the table between page loads and regenerate it as the dynamic controls are not stored between requests. (An advantage of using a ListView, DataGrid etc.).
public partial class WebForm1 : System.Web.UI.Page
{
private List<string> CurrentTestData
{
get
{
if (ViewState["CurrentTestData"] == null)
return new List<string>();
else
return (List<string>)ViewState["CurrentTestData"];
}
set
{
ViewState["CurrentTestData"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
CurrentTestData = getTestData();
GenerateTable(CurrentTestData);
}
else
GenerateTable(CurrentTestData);
}
private List<string> getTestData()
{
List<string> tData = new List<string>();
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
tData.Add("proc" + (CurrentTestData.Count + i) + "_" + rand.Next(100) + "_" + rand.Next(100));
}
return tData;
}
protected void btnClear_Click(object sender, EventArgs e)
{
ClearTheTable();
CurrentTestData = null;
}
protected void btnLoad_Click(object sender, EventArgs e)
{
var CombinedTestData = CurrentTestData;
CombinedTestData.AddRange(getTestData());
CurrentTestData = CombinedTestData;
GenerateTable(CurrentTestData);
}
protected void btnKill_Click(object sender, EventArgs e)
{
lblMsg.Text = "You pressed button " + ((Button)sender).Text;
}
private void GenerateTable(List<string> list)
{
ClearTheTable();
int st = 0;
foreach (string line in list)
{
TableRow tr = new TableRow();
Processes.Controls.Add(tr);
foreach (String str in line.Split('_'))
{
int index = tr.Cells.Add(new TableCell());
tr.Cells[index].Text = str;
}
Button b = new Button();
b.Text = "Kill " + st;
b.ID = "btnKill_" + st;
b.Click += new EventHandler(btnKill_Click);
TableCell tc = new TableCell();
tc.Controls.Add(b);
tr.Cells.Add(tc);
tr.TableSection = TableRowSection.TableBody;
st++;
}
Processes.BorderStyle = BorderStyle.Solid;
Processes.GridLines = GridLines.Both;
Processes.BorderWidth = 2;
}
private void ClearTheTable()
{
for (int i = Processes.Rows.Count; i > 1; i--)
{
Processes.Rows.RemoveAt(i - 1);
}
}
}
Two nice links for you:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click.aspx
http://www.youcanlearnseries.com/Programming%20Tips/CSharp/SetEvents.aspx

Categories

Resources