Link button to display grid view asp.net dynamically - c#

I have to display n grids, n is variable, then I dont know how many grids I'll have.
My problem is, I have to init this grids with Visible false and when click in a button show the grid specific for that button, then how can I link a button to a gridview?
My code that generate the grids:
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view"+i;
grv.Visible = false;
grv.DataSource = dt;
grv.DataBind();
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br /><br />";
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["DESC_OCORRENCIA"].ToString();
tipoOcorrencia = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(tipoOcorrencia);
int quantidade = lst.Count;
lblTipo.Text = tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button"+i;
lkBtn.Text = "+";
place_grids.Controls.Add(lblBlankLines);
place_grids.Controls.Add(lkBtn);
place_grids.Controls.Add(lblTipo);
place_grids.Controls.Add(grv);
place_grids.DataBind();
i++;
}
Thanks in advance.

Modify your foreach loop as below.
private void GenerateControls()
{
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view" + i;
//grv.Visible = false;//Commented as the grid needs be generated on client side, in order to make it visible from JavaScript/jQuery
grv.Attributes.Add("style", "display:none;");
grv.DataSource = dt;
grv.DataBind();
//Adding dynamic link button
LinkButton lnkButton = new LinkButton();
lnkButton.Text = "button " + i;
//lnkButton.Click += new EventHandler(lnkButton_Click);
lnkButton.ID = "lnkButton" + i;
lnkButton.OnClientClick = "ShowGrid('" + grv.ClientID + "');";
Label lblTipo = new Label();
lblTipo.Text = "text " + i;
lblTipo.ID = "lbl" + i;
tempPanel.Controls.Add(lblTipo);
tempPanel.Controls.Add(grv);
tempPanel.Controls.Add(lnkButton);
tempPanel.DataBind();
i++;
}
}
Then you will have to add a link button click event as below, if you want server side event to fire. (Un-comment the line where event handler is assigned to link button.)
protected void lnkButton_Click(Object sender, EventArgs e)
{
LinkButton lnkButton = (LinkButton)sender;
String index = lnkButton.ID.Substring(lnkButton.ID.Length - 1);
GridView grv = (GridView)tempPanel.FindControl("grid_view" + index);
grv.Visible = true;
}
You will need to add all dynamically added controls in the Page_Init event for maintaining their state. Refer below links can be useful.
Dynamically Created Controls losing data after postback
ViewState in Dynamic Control
Call method GenerateControls from Page_Init event as below.
protected void Page_Init(object sender, EventArgs e)
{
GenerateControls();
}
EDIT :
JavaScript function...
function ShowGrid(gridID) {
document.getElementById(gridID).style.display = ''
}
I have kept the server side click event as it is. But I have commented the line where the event handler is assigned to the link button.

Related

Dynamically created button - onclick event not triggering

I have created a file upload control and a upload button in c# code as below: The controls are getting created and are shown in the UI- aspx
TableCell uploadCell = new TableCell();
uploadCell.ColumnSpan = 4;
tRow.Cells.Add(uploadCell);
FileUpload fu = new FileUpload();
fu.ID = "fu_" + BU + "_" + artifact.LookupValue + artifact.LookupId;
fu.AllowMultiple = false;
Button btnUpload = new Button();
btnUpload.ID = "btnUpload_" + BU + "_" + artifact.LookupValue + artifact.LookupId;
btnUpload.Text = "Upload";
btnUpload.Click += new EventHandler(this.btnUpload_Click);
PostBackTrigger trigger = new PostBackTrigger();
trigger.ControlID = btnUpload.ID;
uploadCell.Controls.Add(fu);
uploadCell.Controls.Add(btnUpload);
Up1.Triggers.Add(trigger);
private void btnUpload_Click(object sender, EventArgs e)
{
}
when I click on the upload button, the click event is not getting fired. I have attached a debug on the btnUpload_Click, but that is not hit.
How to trigger the click event for dynamically added control?

read the texts of run-time added textboxes

I have an application where the user can add any number of tabpages depending on what he/she needs. These tabpages have identical controls (textboxes and labels).
The controls on each tabpages are named like this: (on tabpage1 the controls are named: txtServer1, txtPort1, txtUser1, txtDbName1. if the user clicks the 'add another connection button' the application creates a second tabpage and the controls will be named: txtServer2, txtPort2, txtUser2, txtDbName2) and so on...
for example if the user have multiple tabpages to set-up:
the user clicks the 'add another connection' and the another tabpage with identical controls has been created and the user fills it up with appropriate data:
same thing goes here:
here's the code for dynamically added tabpage with controls:
//when 'add another connection' button is clicked
private void btnAddConnection_Click(object sender, EventArgs e)
{
string tabTitle = "Connection " + (tabControl1.TabCount + 1).ToString();
TabPage tabPage = new TabPage(tabTitle);
tabControl1.TabPages.Add(tabPage);
}
//when another tabpage has been added to tabcontrol
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
//control instances
TextBox txtServer = new TextBox();
TextBox txtPort = new TextBox();
TextBox txtUser = new TextBox();
TextBox txtDbName = new TextBox();
Label lblServer = new Label();
Label lblPort = new Label();
Label lblUser = new Label();
Label lblDbName = new Label();
tabControl1.SelectedTab = tabControl1.TabPages[tabControl1.TabCount - 1]; //select the newly addded tabpage
tabControl1.SelectedTab.BackColor = tabPage1.BackColor; //tabpage background color
//lblServer Properties
lblServer.Location = lblServer1.Location;
lblServer.Text = lblServer1.Text;
lblServer.ForeColor = lblServer1.ForeColor;
lblServer.Name = "lblServer" + tabControl1.TabCount.ToString();
//lblPort Properties
lblPort.Location = lblPort1.Location;
lblPort.Text = lblPort1.Text;
lblPort.ForeColor = lblPort1.ForeColor;
lblPort.Name = "lblPort" + tabControl1.TabCount.ToString();
//lblUser Properties
lblUser.Location = lblUser1.Location;
lblUser.Text = lblUser1.Text;
lblUser.ForeColor = lblUser1.ForeColor;
lblUser.Name = "lblUser" + tabControl1.TabCount.ToString();
//lblDbName Properties
lblDbName.Location = lblDbName1.Location;
lblDbName.Text = lblDbName1.Text;
lblDbName.ForeColor = lblDbName1.ForeColor;
lblDbName.Name = "lblDbName" + tabControl1.TabCount.ToString();
//txtserver properties
txtServer.Location = txtServer1.Location;
txtServer.Width = txtServer1.Width;
txtServer.Height = txtServer1.Height;
txtServer.Font = txtServer1.Font;
txtServer.Name = "txtServer" + tabControl1.TabCount.ToString();
//txtport properties
txtPort.Location = txtPort1.Location;
txtPort.Width = txtPort1.Width;
txtPort.Height = txtPort1.Height;
txtPort.Font = txtPort1.Font;
txtPort.Name = "txtPort" + tabControl1.TabCount.ToString();
//txtuser properties
txtUser.Location = txtUser1.Location;
txtUser.Width = txtUser1.Width;
txtUser.Height = txtUser1.Height;
txtUser.Font = txtUser1.Font;
txtUser.Name = "txtUser" + tabControl1.TabCount.ToString();
//txtdbname properties
txtDbName.Location = txtDbName1.Location;
txtDbName.Width = txtDbName1.Width;
txtDbName.Height = txtDbName1.Height;
txtDbName.Font = txtDbName1.Font;
txtDbName.Name = "txtUser" + tabControl1.TabCount.ToString();
//add controls to tabpage
tabControl1.SelectedTab.Controls.Add(lblServer);
tabControl1.SelectedTab.Controls.Add(lblPort);
tabControl1.SelectedTab.Controls.Add(lblUser);
tabControl1.SelectedTab.Controls.Add(lblDbName);
tabControl1.SelectedTab.Controls.Add(txtServer);
tabControl1.SelectedTab.Controls.Add(txtPort);
tabControl1.SelectedTab.Controls.Add(txtUser);
tabControl1.SelectedTab.Controls.Add(txtDbName);
}
When the user clicks the save button, I want the application to read each text in the textboxes (except for that url text) so that I can save it to a configuration file.
all I can think of is this
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string connection;
for (int i = 1; i <= tabControl1.TabCount; i++ )
{
connection = "server=" + txtServer[i].Text + ";port=" txtPort[i].Text + ";user=" + txtUser[i].Text + ";dbname=" + txtDbName[i];
//save to config file code goes here...
}
}
and I know this is not correct.
any solution for this? thanks :)
This is the simplest way you can try this just use below function to get text from control in tabpage
public string getValue(string controlName, TabPage selectedTab)
{
if (selectedTab.Controls.ContainsKey(controlName)){
TextBox selectedtb = (TextBox)selectedTab.Controls[controlName];
return selectedtb.Text;
}
else
return null;
}
and in your save code use it like below
string connection;
int i = 1;
TabControl.TabPageCollection pages = tabControl1.TabPages;
foreach (TabPage page in pages)
{
connection = "server=" + getValue("txtServer"+i,page) + ";port=" +getValue("txtPort"+i,page) + ";user=" + getValue("txtUser"+i,page) + ";dbname=" + getValue("txtDbName"+i,page);
i++;
//save to config file code goes here...
}
txtServer[i].Text it's true but You have not defined an array.
You can do it like this
//global
List<TextBox> txtServerList= new List<TextBox>();
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
txtServer.Location = txtServer1.Location;
txtServer.Width = txtServer1.Width;
txtServer.Height = txtServer1.Height;
txtServer.Font = txtServer.Font;
txtServer.Name = "txtServer" + tabControl1.TabCount.ToString();
txtServerList.Add(txtServer)
.
.
.
}
Finally
for (int i = 1; i <= tabControl1.TabCount; i++ )
{
connection=txtServerList.get(i).Text + ......
}
You could just loop over the controls and find the matching name, something like this:
foreach(var page in tabControl1.TabPages){
var server = ProcessControls(page.Controls, "txtServer");
//... continue with the others
}
private TextBox ProcessControls(Control ctrlContainer, string name)
{
foreach (Control ctrl in ctrlContainer.Controls)
{
if (ctrl.GetType() == typeof(TextBox))
{
if(ctrl.Name.StartsWith(name))
return (TextBox)ctrl;
}
}
}
You can use an ArrayList to store and access all dynamically added controls. Set a name for each dynamically added controls. It can be based on the size of ArrayList.
I will not show the exact systax of c#.
first
declare an ArrayList or List(Type Safe)
List<Button> buttons = new List<Button>();
We just created a storage for our buttons that will be added at runtime.
void your_event (some parameters) {
Button temp = new Button("Hello");
temp.Name="button_name";
YourMainPanel.Controls.add(temp);
//after creating your button add it to the parent container. of any control where you want this button to be added.
//you can also set the coordinates of the button if you like
//after creating the button we need to add it to our List so that we can
//access it later, since the value of the 'temp' will change after this
//event was invoked in the future.
buttons.add(temp);
}
There are several ways to get the items in List<T>. One is by using index.
void someMethod(some parameters) {
Button button = buttons.ElementAt(index);
}

Why does my function not work?

I use Ajax toolkit.I want create text editor for HTML codes. I found .css file in html link tags and for each of these files, create a LinkButton. I want when user click linkbutton .css file open in editor. I write this code:
string textHtml = "";
List<string> listTextHtml = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
AsyncPostBackTrigger d = new AsyncPostBackTrigger();
if (IsPostBack)
return;
StreamReader re = new StreamReader(string.Concat(Server.MapPath("/"), "\\Engine\\TextFile1.txt"));
while (re.Peek() > 0)
{
txtHtmlCode.Content = txtHtmlCode.Content + re.ReadLine() + "\n";
}
textHtml = txtHtmlCode.Content;
re.Close();
string temp = textHtml;
while (temp.Contains("link"))
{
string s = temp.Substring(temp.IndexOf("link"), temp.IndexOf("/>"));
temp = temp.Substring(temp.IndexOf("/>") + 2);
if (s.IndexOf(".css") >= 0)
{
s = s.Substring(s.IndexOf("href=\"") + 6);
listTextHtml.Add(s.Substring(0, s.IndexOf("\"") - 1));
}
//temp = temp.Substring(temp.IndexOf("href="));
//temp = temp.Substring(temp.IndexOf("\"") + 1);
//listTextHtml.Add(temp.Substring(0, temp.IndexOf("\"") - 1));
//temp = temp.Substring(temp.IndexOf("\"") + 1);
}
int i = 0;
hfString.Value = "";
foreach (var item in listTextHtml)
{
//HtmlGenericControl li = new HtmlGenericControl("li");
LinkButton lb = new LinkButton();
lb.ID = i.ToString();
lb.Text = "Link - " + i.ToString();
//lb.Click += ltnCssLoad_Click;
lb.Click += new EventHandler(this.ltnCssLoad_Click);
//li.Controls.Add(lb);
phTags.Controls.Add(lb);
d.ControlID = i.ToString();
d.EventName = "Click";
//udpMain.Triggers.Add(d);
i++;
hfString.Value += item + "|";
}
}
when click the linkbutton this function must run:
protected void ltnCssLoad_Click(object sender, EventArgs e)
{
LinkButton ClickedLink = (LinkButton)sender;
string[] listText = hfString.Value.Split('|');//string.Concat(Server.MapPath("/"),
StreamReader re = new StreamReader(string.Concat(string.Concat(Server.MapPath("/"), listText[int.Parse(ClickedLink.ID)])));
txtHtmlCode.Content = "";
while (re.Peek() > 0)
{
txtHtmlCode.Content = txtHtmlCode.Content + re.ReadLine() + "\n";
}
re.Close();
}
but when I use break point in function ltnCssLoad_Click, this function not work when I click in linkbutton. How can I fix this?
This is not working because when you click link button or any dynamically added control it causes post back and you have "return"ed in page load event handler if IsPostBack is true.
The pain with using dynamic controls is that you have to recreate them every time (first request as well as subsequent post backs).
Restrict file reading to first request (i.e. put it in !IsPostBack condition) and let link buttons' creation code run after that.

Gridview Edit/Update is not working?

Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.

Update DataGrid inside AJAX accordion

I have an AJAX accordion from the ajax control toolkit on a page with a datagrid inside on of the panels. I have a custom itemtemplate for the one column to create a multiline textbox when I click edit on the row. When I click update on the row, the original content of the textbox gets rendered into the textbox. It is supposed to update and go back to the literal not the textbox. When I put the DataBind() into a !IsPostBack, it doesnt get rendered when I click on the accordion pane. Any ideas?
Code:
protected void Page_Load(object sender, EventArgs e)
{
announ.HeaderStyle.CssClass = "header";
announ.Width = Unit.Percentage(100);
announ.GridLines = GridLines.None;
announ.AutoGenerateColumns = false;
announ.CellPadding = 10;
announ.CellSpacing = 0;
announ.HorizontalAlign = HorizontalAlign.Center;
announ.HeaderStyle.Font.Bold = true;
announ.EnableViewState = false;
announ.AlternatingItemStyle.BackColor = System.Drawing.Color.GhostWhite;
//announ.DeleteCommand += AnnounDeleteCommand;
announ.EditCommand += announ_EditCommand;
announ.UpdateCommand += announ_UpdateCommand;
announ.CancelCommand += announ_CancelCommand;
announ.DataKeyField = "id";
var tc1 = new TemplateColumn
{
HeaderTemplate = new
DataGridTemplate(ListItemType.Header, "Announcement"),
ItemTemplate = new DataGridTemplate(ListItemType.Item, "announcement_text"),
EditItemTemplate = new
DataGridTemplate(ListItemType.EditItem, "announcement_text")
};
var editColumn = new EditCommandColumn
{
ButtonType = ButtonColumnType.PushButton,
HeaderText = "Edit",
EditText = "Edit",
UpdateText = "Update",
CancelText = "Cancel"
};
var dateColumn = new BoundColumn {HeaderText = "Posted On", DataField = "date", ReadOnly = true};
var expirationColumn = new BoundColumn {HeaderText = "Expiration Date", DataField = "expiration_date"};
announ.Columns.Add(tc1);
announ.Columns.Add(dateColumn);
announ.Columns.Add(expirationColumn);
announ.DataSource = myAnnouncements;
announ.DataBind();
var deptMgtaccord = new Accordion
{
ID = "deptMgtaccord",
HeaderCssClass = "accordion-header",
HeaderSelectedCssClass = "accordion-headerSelected",
AutoSize = AutoSize.None,
SelectedIndex = 0,
FadeTransitions = true,
TransitionDuration = 250,
FramesPerSecond = 40,
RequireOpenedPane = false,
SuppressHeaderPostbacks = true
};
if (IsPostBack)
{
deptMgtaccord.SelectedIndex = selected;
}
var announcementPane = new AccordionPane {ID = "announcementPane"};
announcementPane.HeaderContainer.Attributes.Add("onmouseover", "this.style.backgroundColor='#e3e2e2';");
announcementPane.HeaderContainer.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';");
announcementPane.HeaderContainer.Controls.Add(new LiteralControl("Announcements >>"));
announcementPane.ContentContainer.Controls.Add(announ);
deptMgtaccord.Panes.Add(announcementPane);
var statsPane = new AccordionPane {ID = "statsPane"};
statsPane.HeaderContainer.Attributes.Add("onmouseover", "this.style.backgroundColor='#e3e2e2';");
statsPane.HeaderContainer.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';");
statsPane.HeaderContainer.Controls.Add(new LiteralControl("Statistics >>"));
statsPane.ContentContainer.Controls.Add(new LiteralControl("Stats"));
deptMgtaccord.Panes.Add(statsPane);
ph1.Controls.Add(deptMgtaccord);
}
protected void announ_CancelCommand(object source, DataGridCommandEventArgs e)
{
announ.EditItemIndex = -1;
announ.DataBind();
}
protected void announ_UpdateCommand(object source, DataGridCommandEventArgs e)
{
var dc = new MTCDataDataContext();
var announText = (TextBox) e.Item.Cells[1].Controls[1];
int announId = (int)announ.DataKeys[e.Item.ItemIndex];
var currentAnnoun = (from a in dc.announcements
where a.id == announId
select a).SingleOrDefault();
currentAnnoun.announcement_text = announText.Text;
dc.SubmitChanges();
announ.EditItemIndex = -1;
announ.DataBind();
}
protected void announ_EditCommand(object source, DataGridCommandEventArgs e)
{
announ.EditItemIndex = e.Item.ItemIndex;
announ.DataBind();
}
public class DataGridTemplate : ITemplate
{
ListItemType templateType;
string columnName;
public DataGridTemplate(ListItemType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(Control container)
{
Literal lc = new Literal();
TextBox tb = new TextBox();
switch (templateType)
{
case ListItemType.Header:
lc.Text = "<B>" + columnName + "</B>";
container.Controls.Add(lc);
break;
case ListItemType.Item:
lc.DataBinding += lc_DataBinding;
container.Controls.Add(lc);
break;
case ListItemType.EditItem:
tb.TextMode = TextBoxMode.MultiLine;
tb.Rows = 6;
tb.Columns = 57;
tb.DataBinding += tb_DataBinding;
container.Controls.Add(tb);
break;
case ListItemType.Footer:
lc.Text = "<I>" + columnName + "</I>";
container.Controls.Add(lc);
break;
}
}
void tb_DataBinding(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
DataGridItem row = (DataGridItem)tb.NamingContainer;
tb.ID = "txt_" + row.ItemIndex;
tb.Text = DataBinder.Eval(row.DataItem, columnName).ToString();
}
void lc_DataBinding(object sender, EventArgs e)
{
Literal lc = (Literal)sender;
DataGridItem row = (DataGridItem)lc.NamingContainer;
lc.ID = "txt_" + row.ItemIndex;
lc.Text = DataBinder.Eval(row.DataItem, columnName).ToString();
}
}
You need to add your dynamic controls in PreInit on every request in order for the controls to get back into the ControlTree and raise events.
Page Event:
PreInit
Typical Use:
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Check the IsPostBack property to determine whether this is the first
time the page is being processed. The
IsCallback and IsCrossPagePostBack
properties have also been set at this
time.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
Note: If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

Categories