I have the following class which is the class for creating a gridview dynamic:
public class DynamicGridViewImageButtonTemplate : ITemplate
{
string _ColName;
DataControlRowType _rowType;
int _Count;
int _Kind;
public DynamicGridViewImageButtonTemplate(string ColName, DataControlRowType RowType, int Kind)
{
_ColName = ColName;
_rowType = RowType;
_Kind = Kind;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.DataRow:
if (_Kind == 0)
{
Label lbl = new Label();
lbl.DataBinding += new EventHandler(this.lbl_DataBind);
container.Controls.Add(lbl);
}
else
if (_Kind == 1)
{
ImageButton vImageButton = new ImageButton();
vImageButton.ID = "btnGetVoucher";
vImageButton.CommandArgument = string.Format("<%# Eval({0}) %>", "Voucher");
vImageButton.CssClass = "divButton";
vImageButton.Height = 25;
vImageButton.Width = 25;
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
vImageButton.DataBinding += new EventHandler(this.imgBtn_DataBind);
container.Controls.Add(vImageButton);
}
break;
default:
break;
}
}
and the following c# code for assigning methods runtime to the imagebutton which I have created in a column:
protected void btnGetVoucher_Command(object sender, CommandEventArgs e)
{
ImageButton btn = sender as ImageButton;
}
protected void gridview_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton vImageButton = (ImageButton)e.Row.FindControl("btnGetVoucher");
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
}
}
and the creating of the gridcolumn is as follows:
GridView vGridView = new GridView();
vGridView.RowCreated += new GridViewRowEventHandler(gridview_RowCreated);
vTemplateField = new TemplateField();
vTemplateField.HeaderTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.Header, 0);
vTemplateField.ItemTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.DataRow, 1);
vGridView.Columns.Add(vTemplateField);
And at last the databind here:
private void imgBtn_DataBind(Object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
btn.CommandArgument = DataBinder.Eval(row.DataItem, "Voucher").ToString();
}
But I can't step into the method btnGetVoucher_Command :-( I think that everything has been made correctly - but there must be something I have missed somewhere...
I can access the button in my Row_Created routine - but afterwards not use the GetVoucherCommand :-( the event is not fired :-(
So my question is why can't I step into that routine?
Thanks in advance,
Michael
Update:
The full class is here...
public class DynamicGridViewTextTemplate : ITemplate
{
string _ColNameText;
DataControlRowType _rowType;
public DynamicGridViewTextTemplate(string ColNameText, DataControlRowType RowType)
{
_ColNameText = ColNameText;
_rowType = RowType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = "<b>" + _ColNameText + "</b>";
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
ImageButton vImageButton = new ImageButton();
vImageButton.ID = "btnGetVoucher";
vImageButton.ImageUrl = "~/Images/Icons/icons8-download-from-the-cloud-50.png";
vImageButton.PostBackUrl = "#DownloadVoucher";
vImageButton.CommandArgument = string.Format("<%# Eval({0}) %>", "Voucher");
vImageButton.ToolTip = "Se og download bilag";
vImageButton.CssClass = "divButton";
vImageButton.Height = 25;
vImageButton.Width = 25;
vImageButton.DataBinding += new EventHandler(this.imgBtn_DataBind);
vImageButton.CommandName = "DownloadVoucher";
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
container.Controls.Add(vImageButton);
break;
default:
break;
}
}
private void imgBtn_DataBind(Object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
btn.CommandArgument = DataBinder.Eval(row.DataItem, _ColNameText).ToString();
}
}
public class DynamicGridViewImageButtonTemplate : ITemplate
{
string _ColNameText;
DataControlRowType _rowType;
public DynamicGridViewImageButtonTemplate(string ColNameText, DataControlRowType RowType)
{
_ColNameText = ColNameText;
_rowType = RowType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = "<b>" + _ColNameText + "</b>";
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
ImageButton vImageButton = new ImageButton();
vImageButton.ID = "btnGetVoucher";
vImageButton.ImageUrl = "~/Images/Icons/icons8-download-from-the-cloud-50.png";
vImageButton.PostBackUrl = "#DownloadVoucher";
vImageButton.CommandArgument = string.Format("<%# Eval({0}) %>", "Voucher");
vImageButton.ToolTip = "Se og download bilag";
vImageButton.CssClass = "divButton";
vImageButton.Height = 25;
vImageButton.Width = 25;
vImageButton.DataBinding += new EventHandler(this.imgBtn_DataBind);
vImageButton.CommandName = "DownloadVoucher";
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
container.Controls.Add(vImageButton);
break;
default:
break;
}
}
protected void btnGetVoucher_Command(object sender, CommandEventArgs e)
{
ImageButton btn = sender as ImageButton;
}
private void imgBtn_DataBind(Object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
btn.CommandArgument = DataBinder.Eval(row.DataItem, _ColNameText).ToString();
}
}
The events is here...
protected void gridview_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton vImageButton = (ImageButton)e.Row.FindControl("btnGetVoucher");
}
}
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton vImageButton = (ImageButton)e.Row.FindControl("btnGetVoucher");
}
}
protected void gridview_RowCommand(object sender, CommandEventArgs e)
{
if (e.CommandName == "DownloadVoucher")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView grid = sender as GridView;
GridViewRow row = grid.Rows[index];
ImageButton vImageButton = (ImageButton)row.FindControl("btnGetVoucher");
}
}
The creating of the gridview is here...
GridView vGridView = new GridView();
vGridView.AutoGenerateColumns = false;
vGridView.ShowHeaderWhenEmpty = true;
vGridView.ShowHeader = true;
vGridView.HeaderStyle.BackColor = System.Drawing.ColorTranslator.FromHtml("#C6E0B4");
vGridView.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
vGridView.RowCreated += new GridViewRowEventHandler(gridview_RowCreated);
vGridView.RowDataBound += new GridViewRowEventHandler(gridview_RowDataBound);
vGridView.RowCommand += new GridViewCommandEventHandler(gridview_RowCommand);
vTemplateField = new TemplateField();
vTemplateField.HeaderTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.Header);
vTemplateField.ItemTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.DataRow);
vGridView.Columns.Add(vTemplateField);
micheal.
in this code, i can't see event handling code in InstantiateIn method.
ex) like this.
lbl.DataBinding += new EventHandler(this.btnGetVoucher_Command);
DynamicGridViewTextTemplate class constructor args are 3 count.
but, when using DynamicGridViewTextTemplate constructor,
used only 2 count args.
where is kind?
try it.
vTemplateField.HeaderTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.Header, 0);
vTemplateField.ItemTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.DataRow, 1);
best example in msdn
https://learn.microsoft.com/ko-kr/dotnet/api/system.web.ui.webcontrols.templatefield.-ctor?view=netframework-4.8
I hope this answer helps you.
Related
I am creating dynamic textboxes when clicking on a set of different radio button. Below is an example of two radio button onclick event.
protected void Checkbox1_CheckedChanged(object sender, EventArgs e)
{
string servicename = "service1";
if (checkbox1.Checked)
{
InputParameters.InputParameters aa= new InputParameters.InputParameters();
textbox = aa.GetInputFields(servicename);
for (int i=0;i<textbox.Count;i++)
{
// declare a textbox
TextBox CPDT = new TextBox();
CPDT.ID = servicename + i.ToString();
CPDT.CssClass = "form-control";
CPDT.EnableViewState = true;
Label lblCPD=new Label();
lblCPD.ID = "txtDynamiclbl" + servicename+ i.ToString();
lblCPD.CssClass= "form-control-label";
lblCPD.Text= textbox[i].ToString();
lblCPD.EnableViewState = true;
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
//this.NumberOfControls++;
}
Button callSoap = new Button();
callSoap.ID = "txtDynamicSearch" + servicename;
callSoap.Text = "Search";
callSoap.CssClass = ".btn-info";
callSoap.CommandArgument = "test";
callSoap.Click += new EventHandler(btnsoap);
callSoap.EnableViewState = true;
CPDPlaceHolder.Controls.Add(callSoap);
}
else
{
}
}
protected void Checkbox2_CheckedChanged(object sender, EventArgs e)
{
string servicename = "service2";
if (checkbox2.Checked)
{
InputParameters.InputParameters aa = new InputParameters.InputParameters();
List<String> textbox = aa.GetInputFields("test1");
// textboxs.AddRange(textbox);
for (int i = 0; i < textbox.Count; i++)
{
// declare a textbox
TextBox CPDT = new TextBox();
CPDT.ID = servicename + i.ToString();
CPDT.CssClass = "form-control";
Label lblCPD = new Label();
lblCPD.ID = "txtDynamiclbl" + servicename + i.ToString();
lblCPD.CssClass = "form-control-label";
lblCPD.Text = textbox[i].ToString();
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
}
Button callSoap = new Button();
callSoap.ID = "txtDynamicSearch" + servicename;
callSoap.Text = "Search";
callSoap.CssClass = ".btn-info";
callSoap.CommandArgument = "test1";
callSoap.Click += new EventHandler(btnsoap);
callSoap.EnableViewState = true;
CPDPlaceHolder.Controls.Add(callSoap);
}
else
{
}
}
The textboxes and search button appears as needed. The problem now is when i clicked on the search button a post back occur and all the controls are gone. I have been reading a lot about initialising the controls in page_preinit and i tried the code below.
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
try
{
foreach (string key in keys)
{
TextBox CPDT = new TextBox();
CPDT.ID = "test" + i.ToString();
CPDT.CssClass = "form-control";
Label lblCPD = new Label();
lblCPD.ID = "txtDynamiclbl" + "test" + i.ToString();
lblCPD.CssClass = "form-control-label";
lblCPD.Text = textbox[i].ToString();
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
i++;
}
}
catch
{
}
}
In the above function this line only returns the search button and not the texboxes. I am stuck on this issue.
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
T
I'm trying to get Tweet ID via TweetInvi API but always get null point exception. I'm out of options and can't understand what i did wrong. Here is my code. Problem occurs when i select desired Item from view and press retweet.
namespace MIF_TwitterApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Auth.SetUserCredentials("KEY", "KEY", "KEY",
"KEY");
}
private void Form1_Load(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
//PROFILE
profileImage.ImageLocation = user.ProfileImageUrlFullSize;
nameLabel.Text = user.Name;
usernameLabel.Text = "#" + user.ScreenName;
followersLabel.Text = "Followers: " + user.FollowersCount;
}
//Tweeting with PICS
private void tweetBtn_Click(object sender, EventArgs e)
{
if (tweetBox.Text != "")
{
if (imgUploadPath.Text != "")
{
byte[] file = File.ReadAllBytes(imgPreview.ImageLocation);
Tweet.PublishTweetWithImage(tweetBox.Text, file);
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
tweetBox.Clear();
MessageBox.Show("Tweet posted!");
}
else
{
Tweet.PublishTweet(tweetBox.Text);
MessageBox.Show("Tweet posted!");
tweetBox.Clear();
}
}
else
{
MessageBox.Show("Please enter text!");
tweetBox.Clear();
}
}
private void addImg_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
imgPreview.ImageLocation = ofd.FileName;
imgUploadPath.Text = ofd.FileName;
}
private void dropImg_Click(object sender, EventArgs e)
{
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
}
private void timelineBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetHomeTimeline(40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void postsBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetUserTimeline(user, 40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void retweetBtn_Click(object sender, EventArgs e)
{
var checkedItems = listView1.SelectedItems;
long a = (long)listView1.SelectedItems[0].Tag;
var user = User.GetAuthenticatedUser();
var retweet = Tweet.PublishRetweet(a);
MessageBox.Show("Retweet was successfull");
listView1.Items.Clear();
}
}
}
Breakes on long a, I can't figure out how to get that Long Tweet ID
Here is the full code
Problem was that my X was not incrementing correctly as it was out of for loop.
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
x = x +1;
}
protected void RadButton1_Click(object sender, EventArgs e)
{
RadTreeList1.ItemCommand -= new EventHandler<TreeListCommandEventArgs>(RadTreeList1_ItemCommand);
RadButton radbutton1 = (RadButton)Form.FindControl("RadButton1");
TreeListDataItem dataItem = e.Item as TreeListDataItem;
Hashtable table = new Hashtable();
table["RowId"] = (dataItem.FindControl("Label1") as Label).Text;
table["Alias"] = (dataItem.FindControl("Label2") as Label).Text;
}
There I am getting error at Item as i dont have TreeListCommandEventArgs in radbutton pls help me in this
If I replace EventArgs with TreeListCommandEventArgs that doesnt meaningul and becomes error at runtime.....
protected void RadButton1_Click(object sender, EventArgs e)
{
RadTreeList1.ItemCommand -= new EventHandler<TreeListCommandEventArgs>(RadTreeList1_ItemCommand);
ContentPlaceHolder contentPage = this.Page.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
RadButton R = sender as RadButton;
RadButton radbutton1 = R.Parent.FindControl("RadButton1") as RadButton;
CommandEventArgs e2 = new CommandEventArgs(null, radbutton1.CommandArgument);
TreeListCommandEventArgs e1 = new TreeListCommandEventArgs(null, radbutton1.CommandArgument, e2);
TreeListDataItem dataItem = e1.Item as TreeListDataItem;
Hashtable table = new Hashtable();
table["RowId"] = (dataItem.FindControl("Label1") as Label).Text;
table["Alias"] = (dataItem.FindControl("Label2") as Label).Text;
}
protected void RadButton1_Click(object sender, EventArgs e)
{
ContentPlaceHolder contentPage = Page.Master.FindControl("ContentPlaceHolder2") as ContentPlaceHolder;
RadButton radbutton1 = (RadButton)contentPage.FindControl("RadButton1");
object mysender = (object)radbutton1;
CommandEventArgs e2 = new CommandEventArgs(null, radbutton1.CommandArgument);
RadButton1_Click(mysender, e2);
TreeListCommandEventArgs e1 = new TreeListCommandEventArgs(null,radbutton1.CommandArgument,e2);
TreeListDataItem dataItem = e1.Item as TreeListDataItem;
Hashtable table = new Hashtable();
table["RowId"] = (dataItem.FindControl("Label1") as Label).Text;
table["Alias"] = (dataItem.FindControl("Label2") as Label).Text;
}
In the page_load I'm creating dynamically the headers using data from SpGetCompanies, which is working fine. Then I'm trying to add a ListView to every dynamically created accordion pane with the data source SpSearchPublicationsTop1.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
SQLConnection dataAccessor = new SQLConnection();
dtCompanies = dataAccessor.SpGetCompanies();
if (dtCompanies.Rows.Count > 0)
{
AccordionPane pn;
Label lblContent;
int j = 0;
for (int i = 0; i < dtCompanies.Rows.Count; i++)
{
lblHeader = new Label();
lblHeader.Text = dtCompanies.Rows[i][1].ToString();
lblContent = new Label();
lblContent.Text = "Hallo";
pn = new AccordionPane();
pn.ID = "Pane" + j;
pn.HeaderContainer.Controls.Add(lblHeader);
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
//view = (ListView)FindControl("lv_result");
view.DataSource = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
view.DataBind();
#region commented stuff
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// //view = (ListView)FindControl("lv_result");
// //column1.Text = dt2.Rows[0][0].ToString();
// //view.Columns.Add(column1);
// //Label lblAcronym = new Label();
// //lblAcronym.Text = dt2.Rows[0][0].ToString();
// //view.DataSource = lblAcronym;
// view.DataSource = dt2;
// view.DataBind();
//}
//listView1.Columns.Add(column1);
//foreach (DataRow dr in dt2.Rows)
//{
// ListViewItem lvi = new ListViewItem(dr[0].ToString()); //1.st column in datatable, instead of 0 you can write column`s name like: ["CustomerID"]
// lvi.SubItems.Add(dr[1].ToString()); //2nd column from datatable
// view.Items.Add(lvi);
//}
//this.Controls.Add(view);
//ListView lv_result = new ListView();
////lv_result.ItemTemplate = new ItemTemplate();
//lv_result.ID = "lvpane" + i;
//lv_result.Visible = true;
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// lv_result.DataSource = dt2;
// lv_result.DataBind();
//}
//var level2 = (ListView)FindControl("lv_result");
//level2.ItemTemplate = view.ItemTemplate;
////level2.DataSource = dt2(e.AccordionItem.DataItemIndex);
////level2.DataBind();
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// level2.DataSource = dt2;
// level2.DataBind();
//}
#endregion
pn.ContentContainer.Controls.Add(view);
//pn.ContentContainer.Controls.Add(lblContent);
Accordion1.Panes.Add(pn);
++j;
}
}
}
}
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add(new Literal() { Text = dataItem.ToString() });
}
}
With the code above the headers from the accordion are working fine, but instead of the ListView data in the content I'm only getting: System.Data.DataRowView
What am I doing wrong?
You are missing a call to:
DataBinder.Eval(container.DataItem, "YouBindingProperty");
Example:
public void DataBinding(object sender, EventArgs e)
{
var genericControl = (HtmlGenericControl)sender;
var container = (ListViewDataItem)container.NamingContainer;
container.Controls.Add(new Literal() { Text = DataBinder.Eval(container.DataItem, "YouBindingProperty") });
}
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.