I have created 2 radwizard steps dynamically, i want to fire an ajax request on step change. How can i do this?
Thanks.
Markup:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WizardUCDemo.ascx.cs" Inherits="WebUIFrameWork.UITemplate.WizardUCDemo" %>
<div style="overflow:inherit">
<telerik:RadWizard runat="server" RenderMode="Lightweight" ID="wizardControl"
DisplayProgressBar="false" ProgressBarPosition="Right" NavigationBarPosition="Right"
NavigationButtonsPosition="Bottom" DisplayNavigationButtons="false">
</telerik:RadWizard>
</div>
userControl.ascx.cs:
public void GenerateSteps()
RadWizardStep step;
for (int i = 0; i < 2; i++)
{
step = new RadWizardStep();
step.ClientIDMode = ClientIDMode.Static;
step.ID = "step_1"+i.ToString();
wizardControl.WizardSteps.Add(step);
}
aspx.cs:
protected void rbtnAddControl_Click(object sender, EventArgs e)
{
WizardUCDemo.GenerateSteps();
}
protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
}
image
Related
Currently I'm working on a webform app and I populate the DevExpress grid on selected value from a ASPxComboBox. I have this part working no problem. However my requirement is to refresh the grid if there is any new data added into the database so the users can see this. So I've added a button and on the click event I try to refresh the data but the grid doesn't refresh. If I step through the code I can see that the new values from the database are there in my DataTable. I can't seem to figure out what could be causing the grid to not refresh. Any help would be highly appreciated.
This is what I have so far
SelectedIndexChangedEvent
protected void TrainingOptions_SelectedIndexChanged(object sender, EventArgs e)
{
ASPxComboBox ddl = (ASPxComboBox)sender;
string[] parameters = { ddl.SelectedItem.Value.ToString() };
TrainingGrid.DataSource = dto.PopulateTrainingData(parameters);
TrainingGrid.DataBind();
}
ButtonClickEvent
protected void Refresh_Click(object sender, EventArgs e)
{
string[] parameters = { TrainingOptions.SelectedItem.Value.ToString() };
TrainingGrid.DataSource = dto.PopulateTrainingData(parameters);
TrainingGrid.DataBind();
}
PopulateTrainingDara
public DataTable PopulateTrainingData(params string[] parameters)
{
//Loop through DataTable Here
...
HttpContext.Current.Session["GridDT"] = mainTable;
return mainTable;
}
DataBinding
protected void TrainingGrid_DataBinding(object sender, EventArgs e)
{
TrainingGrid.DataSource = Session["GridDT"];
}
Page_LoadEvent
if (!IsPostBack)
{
DataTable dropDownOptions = dto.GetTrainingData("MyQuery");
//Add datasource to TrainingOptions dropdown
TrainingOptions.DataSource = dropDownOptions;
TrainingOptions.Text = "Please choose";
TrainingOptions.TextField = "ID";
TrainingOptions.DataBindItems();
}
Markup
<dx:ASPxComboBox ID="TrainingOptions" runat="server" ValueType="System.String" OnSelectedIndexChanged="TrainingOptions_SelectedIndexChanged" CssClass="combo-box"></dx:ASPxComboBox>
<dx:ASPxGridView ID="TrainingGrid" runat="server" OnHtmlDataCellPrepared="TrainingGrid_HtmlDataCellPrepared" OnDataBinding="TrainingGrid_DataBinding"></dx:ASPxGridView>
<dx:ASPxButton ID="Refresh" runat="server" Text="Refresh" OnClick="Refresh_Click" AutoPostBack="false"></dx:ASPxButton>
Note: I am not populating the grid in the Page_Load event.
If any other information is required please let me know.
Ok, so I've recreated your example with the latest trial version of DevExpress Suite. I removed unnecessary code and this is the code that works in my case:
public partial class DevExpress : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dropDownOptions = new DataTable();
dropDownOptions.Columns.Add("id");
DataRow row = dropDownOptions.NewRow();
row["id"] = 1;
dropDownOptions.Rows.Add(row);
row = dropDownOptions.NewRow();
row["id"] = 2;
dropDownOptions.Rows.Add(row);
dropDownOptions.AcceptChanges();
TrainingOptions.DataSource = dropDownOptions;
TrainingOptions.Text = "Please choose";
TrainingOptions.TextField = "ID";
TrainingOptions.DataBindItems();
}
}
protected void Refresh_Click(object sender, EventArgs e)
{
string[] parameters = { TrainingOptions.SelectedItem.Value.ToString() };
TrainingGrid.DataSource = PopulateTrainingData(parameters);
TrainingGrid.DataBind();
}
protected void TrainingOptions_SelectedIndexChanged(object sender, EventArgs e)
{
ASPxComboBox ddl = (ASPxComboBox)sender;
string[] parameters = { ddl.SelectedItem.Value.ToString() };
TrainingGrid.DataSource = PopulateTrainingData(parameters);
TrainingGrid.DataBind();
}
public DataTable PopulateTrainingData(params string[] parameters)
{
DataTable mainTable = (DataTable)Session["GridDT"] ?? new DataTable();
if (!mainTable.Columns.Contains("id"))
{
mainTable.Columns.Add("id");
}
DataRow row = mainTable.NewRow();
row["id"] = parameters[0];
mainTable.Rows.Add(row);
mainTable.AcceptChanges();
HttpContext.Current.Session["GridDT"] = mainTable;
return mainTable;
}
}
And the aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="DevExpress.aspx.cs" Inherits="WebApplication1.DevExpress" %>
<%# Register Assembly="DevExpress.Web.v15.2, Version=15.2.7.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web" TagPrefix="dx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<dx:ASPxComboBox ID="TrainingOptions" runat="server" ValueType="System.String" OnSelectedIndexChanged="TrainingOptions_SelectedIndexChanged" AutoPostBack="true" CssClass="combo-box"></dx:ASPxComboBox>
<dx:ASPxGridView ID="TrainingGrid" runat="server"></dx:ASPxGridView>
<dx:ASPxButton ID="Refresh" runat="server" Text="Refresh" OnClick="Refresh_Click"></dx:ASPxButton>
</asp:Content>
If this is not working for you you should check which version of DevExpress controls are you using and maybe update them if its possible. Or maybe you are doing something more which you didn't post here.
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 :)
When I choice row at GridView of UserControl.This gridview disappear.
Main page (aspx page)
1.1.Html
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plh" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
1.2.CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Test2.Admin.WebUserControl1[] wuc = new Test2.Admin.WebUserControl1[2];
for (int i = 0; i < 2; i++)
{
plh.Controls.Add(new LiteralControl("<div id='dvChannel' runat='server' style='width: 200px;float:left;padding-left:20px;'>"));
wuc[i] = (Test2.Admin.WebUserControl1)LoadControl("WebUserControl1.ascx");
wuc[i].ID = "wuc" + i.ToString();
plh.Controls.Add(wuc[i]);
plh.Controls.Add(new LiteralControl("</div>"));
}
}
}
UserControl
2.1.html
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="Test2.Admin.WebUserControl1" %>
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="true"
OnSelectedIndexChanged="gvSelected">
</asp:GridView>
2.2.Codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var list = (new[] {
new { Price = 30 } ,
new { Price = 30 },
new { Price = 30 },
new { Price = 30 }
});
GridView1.DataSource = list;
GridView1.DataBind();
}
}
protected void gvSelected(object sender,EventArgs e)
{
GridViewRow row = GridView1.Rows[GridView1.SelectedIndex];
row.BackColor = Color.Red;//Set red color for this row on gridview
}
When I choice row at GridView of UserControl.This gridview disappear.
What should I do for getting it work correct.
Do you have any solution?
You need to Load the GridView even in Postbacks.
Try removing the condition - if (!Page.IsPostBack)
Or, write a different code snippet in else block - for setting the datasource & binding the Grid.
I have the feeling that i'm missing something key here.
I've tried following guides on http://msdn.microsoft.com/en-us/magazine/cc300437.aspx
and on google, but i can't see what i haven't done.
I have some very basic code which i have written just trying to get this to work:
The Default.aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableSessionState="True" %>
<!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>Demo Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="myLabel" runat="server" Text="foo"></asp:Label>
<asp:LinkButton ID="lnkClickButton" runat="server" OnClick="lnkClickButton_Click" CommandName="Clicky">Click Me</asp:LinkButton>
</div>
</form>
</body>
</html>
The Default.aspx.cs code:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["clickcount"] = 0;
Cache["clickscount"] = 0;
}
protected void lnkClickButton_Click(object sender, EventArgs e)
{
Session["clickcount"] = (int)Session["clickcount"] + 1;
Cache["clickscount"] = (int)Cache["clickscount"] + 1;
Label myLabel = ((Label)this.FindControl("myLabel"));
if (myLabel != null)
{
myLabel.Text = "Session: " + Session["clickcount"] + "; Cache: " + Cache["clickscount"] + ";";
}
}
}
I've tried using both the session object and the cache object to increment the values, but to no avail. I just get 1 every time.
N.B. this is my first asp.net project, also i'm fairly new to c#.
Page_Load is ran every postback as well as the initial load. You need to specify no postback in your Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
Session["clickcount"] = 0;
Cache["clickscount"] = 0;
}
}
Better still, specify that it should only be set if it doesn't already have a value:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["clickcount"] == null){
Session["clickcount"] = 0;
}
}
Just to clarify, the reason that it is better to only set the value if it isn't already set is that Page.IsPostBack is false every time someone directly visits the page. Say for instance you have your page http://example.com/Demo/Default.aspx and at the top you have a logo which you wrap in logo here, the session would be reset every time somebody clicked on the logo, even though they didn't actually leave the page. Also happens if they refresh on their browser without re-posting the last post.
Read on MSDN : Page.IsPostBack Property - Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
vlue of property is true if the page is being loaded in response to a client postback; otherwise, false.
code like this ...you need to put the code in !IsPostBack as like below
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["clickcount"] = 0;
Cache["clickscount"] = 0;
}
}
serverside control generate postback to page it self so the code that you dont wnat to execute on each postbck need to be put as above
this will resolve your issue easily...
further to this you can create static property for count like this
Check my post on : Programming Practice for Server Side State Maintenance Variable
private int ClickCount
{
get
{
if (Session["clickcount"] == null)
{ Session["clickcount"] = 0; return 0; }
else
return (int)Session["clickcount"] ;
}
set
{
Session["clickcount"] = value;
}
}
than in final code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ClickCount = 0;
}
}
protected void lnkClickButton_Click(object sender, EventArgs e)
{
int val = ClickCount ;
ClickCount = val + 1;
}
Writing:
Session["clickcount"] = 0;
In the Page_Load will cause the counter to be reset every time the user enters the page.
Seems to me you want something like this:
protected void lnkClickButton_Click(object sender, EventArgs e)
{
if (Session["clickcount"] == null)
{
Session["clickcount"] = 1;
}
else
{
Session["clickscount"] = (int)Session["clickscount"] + 1;
}
Label myLabel = ((Label)this.FindControl("myLabel"));
if (myLabel != null)
{
myLabel.Text = "Session: " + Session["clickcount"] + ";
}
}
You get 1 because every post back your session and cache variable equal to 0.
protected void Page_Load(object sender, EventArgs e)
{
Session["clickcount"] = 0;
Cache["clickscount"] = 0;
}
And button click occur after the page_load, So you should use IsPostback property.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["clickcount"] = 0;
Cache["clickscount"] = 0;
}
}
Now these variables initialize only when page is loaded.
You should go through following link. It is described Asp.net page life.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
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