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.
Related
I'm adding a button in runtime in C# web forms. I need to call a function btnEdit_click when the button is called. Somehow the function isn't being called.
The codes are below. Please help
protected void btnEdit_Click(object sender, EventArgs e)
{
Response.Redirect("~/Setup.aspx");
}
HtmlGenericControl EditButton = new HtmlGenericControl("button");
EditButton.Attributes["class"] = "btn btn-default";
EditButton.Attributes["id"] = "editButton";
EditButton.Attributes["runat"] = "server";
EditButton.Attributes["OnServerClick"] = "btnEdit_Click";
EditButton.InnerText = "Edit";
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
HtmlButton EditButton = new HtmlButton();
EditButton.Attributes["class"] = "btn btn-default";
EditButton.Attributes["id"] = "editButton";
EditButton.Attributes["runat"] = "server";
EditButton.InnerText = "Edit";
EditButton.ServerClick += btnEdit_Click;
this.form1.Controls.Add(EditButton);
}
protected void btnEdit_Click(object sender, EventArgs e)
{
Response.Redirect("~/Setup.aspx");
}
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;
}
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 referred Error with the event handlers of dynamic linkbutton . It says to add event handlers in Page_Init or Page_Load. I tired following code. But the event handler is not fired when I click on the dynamic added link buttons. What need to be corrected here?
Note: The dynamic LinkButton controls are added in the click event of a button after some business validations (the business code is not given for brevity)
Markup
<form id="form1" runat="server">
<div>
<asp:LinkButton ID="lnkTest" runat="server" OnClick="LinkButton_Click">Static LinkButton</asp:LinkButton>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<br />
<asp:PlaceHolder ID="plhDynamicLinks" runat="server"></asp:PlaceHolder>
</div>
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control ctrl in plhDynamicLinks.Controls)
{
LinkButton dynamicButton = (LinkButton)ctrl;
dynamicButton.Click += new EventHandler(LinkButton_Click);
}
if (Page.IsPostBack)
{
}
}
protected void Page_Init(object sender, EventArgs e)
{
int x = 0;
foreach (Control ctrl in plhDynamicLinks.Controls)
{
LinkButton dynamicButton = (LinkButton)ctrl;
dynamicButton.Click += new EventHandler(LinkButton_Click);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
LinkButton clickedControl = (LinkButton)sender;
Response.Write(clickedControl.ID +" Link Button Clicked");
}
protected void btnAdd_Click(object sender, EventArgs e)
{
plhDynamicLinks.Controls.Clear();
LinkButton button1 = new LinkButton();
button1.ID = "D1";
button1.Text = "1";
plhDynamicLinks.Controls.Add(button1);
LinkButton button2 = new LinkButton();
button2.ID = "D2";
button2.Text = "2";
plhDynamicLinks.Controls.Add(button2);
}
It is mandatory to register all the required dynamic controls’ event handlers in the Page_Load/ Page_Init itself. One working example can be seen at Dynamic Control’s Event Handler’s Working
MarkUp
<form id="form1" runat="server">
<div>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<br />
<asp:PlaceHolder ID="plhDynamicLinks" runat="server"></asp:PlaceHolder>
</div>
</form>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
LinkButton lnk1 = new LinkButton();
lnk1.ID = "D1";
lnk1.Text = "A";
//Event handler must be registered in the Page_Load/Page_Init
lnk1.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk1);
LinkButton lnk2 = new LinkButton();
lnk2.ID = "D2";
lnk2.Text = "B";
lnk2.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk2);
LinkButton lnk3 = new LinkButton();
lnk3.ID = "D3";
lnk3.Text = "C";
lnk3.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk3);
LinkButton lnk4 = new LinkButton();
lnk4.ID = "D4";
lnk4.Text = "D";
lnk4.Click += new EventHandler(LinkButton_Click);
plhDynamicLinks.Controls.Add(lnk4);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
PopulateLinksBasedOnCriteria();
LinkButton clickedControl = (LinkButton)sender;
Response.Write(DateTime.Now.ToString()+"___"+ clickedControl.ID + " Link Button Clicked" );
}
protected void btnAdd_Click(object sender, EventArgs e)
{
PopulateLinksBasedOnCriteria();
}
private void PopulateLinksBasedOnCriteria()
{
plhDynamicLinks.Controls.Clear();
if (DateTime.Now.Second < 30)
{
LinkButton linkButton1 = new LinkButton();
linkButton1.ID = "D1";
linkButton1.Text = "1";
plhDynamicLinks.Controls.Add(linkButton1);
LinkButton linkButton2 = new LinkButton();
linkButton2.ID = "D2";
linkButton2.Text = "2";
plhDynamicLinks.Controls.Add(linkButton2);
}
else
{
LinkButton linkButton3 = new LinkButton();
linkButton3.ID = "D3";
linkButton3.Text = "3";
plhDynamicLinks.Controls.Add(linkButton3);
LinkButton linkButton4 = new LinkButton();
linkButton4.ID = "D4";
linkButton4.Text = "4";
plhDynamicLinks.Controls.Add(linkButton4);
}
}
Dynamic controls must be re-created on every postback, this Article is a good link about how to persist dynamic controls and their state.
Add javascript onClick attribute to the dymanic control and set hidden field values which is required for the control event. Onclick of the dymanic grid, the will postback and will get the hidden field value. In page load call a method to do the job if the hidden field has value and make it null after doing the job.
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