OnTextChanged event not firing inside UpdatePanel - both created dynamically - c#

What I am trying to do is to populate column of GridView with textboxes and to execute some function OnTextChanged.
This is my code:
if (e.Row.RowType == DataControlRowType.DataRow)
{
UpdatePanel UP_AmountToBuy = new UpdatePanel();
UP_AmountToBuy.ContentTemplateContainer.Controls.Clear();
UP_AmountToBuy.Triggers.Clear();
UP_AmountToBuy.UpdateMode = UpdatePanelUpdateMode.Conditional;
UP_AmountToBuy.ChildrenAsTriggers = false;
UP_AmountToBuy.Attributes["runat"] = "server";
//Create and add TextBox
TextBox TB_AmountToBuy = new TextBox();
TB_AmountToBuy.Text = "0";
TB_AmountToBuy.TextChanged += new EventHandler(TB_AmountToBuy_TextChanged);
TB_AmountToBuy.Attributes["OnTextChanged"] = "TB_AmountToBuy_TextChanged";
TB_AmountToBuy.Attributes["runat"] = "server";
TB_AmountToBuy.AutoPostBack = true;
TB_AmountToBuy.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
TB_AmountToBuy.ID = "buyID" + count;
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(TB_AmountToBuy);
//Create and add AsyncPostBackTrigger
AsyncPostBackTrigger APBT_trig = new AsyncPostBackTrigger();
APBT_trig.EventName = "TextChanged";
APBT_trig.ControlID = TB_AmountToBuy.ID;
UP_AmountToBuy.Triggers.Add(APBT_trig);
Label newLBL = new Label();
newLBL.Text = "123";
newLBL.Attributes["runat"] = "server";
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(newLBL);
e.Row.Cells[5].Controls.Add(UP_AmountToBuy);
count++;
}
}
public void TB_AmountToBuy_TextChanged(object sender, EventArgs e)
{
((sender as TextBox).Parent.Controls[1] as Label).Text = (sender as TextBox).Text;
}
The problem is, that event OnTextChanged never fired...

Dynamically generated controls needs to be created every time in page load in order to restore their view state ,fire events and get value from them.Like this
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var dt = new System.Data.DataTable();
dt.Columns.Add("Col1");
dt.Rows.Add("Hi");
GridView1.DataSource = dt;
GridView1.DataBind();
}
CreateDynamicControles();
}
public void CreateDynamicControles()
{
var count = 0;
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
UpdatePanel UP_AmountToBuy = new UpdatePanel();
UP_AmountToBuy.ContentTemplateContainer.Controls.Clear();
UP_AmountToBuy.Triggers.Clear();
UP_AmountToBuy.UpdateMode = UpdatePanelUpdateMode.Conditional;
UP_AmountToBuy.ChildrenAsTriggers = false;
UP_AmountToBuy.Attributes["runat"] = "server";
//Create and add TextBox
TextBox TB_AmountToBuy = new TextBox();
TB_AmountToBuy.Text = "0";
TB_AmountToBuy.TextChanged += new EventHandler(TB_AmountToBuy_TextChanged);
TB_AmountToBuy.Attributes["OnTextChanged"] = "TB_AmountToBuy_TextChanged";
TB_AmountToBuy.Attributes["runat"] = "server";
TB_AmountToBuy.AutoPostBack = true;
TB_AmountToBuy.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
TB_AmountToBuy.ID = "buyID" + count;
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(TB_AmountToBuy);
//Create and add AsyncPostBackTrigger
AsyncPostBackTrigger APBT_trig = new AsyncPostBackTrigger();
APBT_trig.EventName = "TextChanged";
APBT_trig.ControlID = TB_AmountToBuy.ID;
UP_AmountToBuy.Triggers.Add(APBT_trig);
Label newLBL = new Label();
newLBL.Text = "123";
newLBL.Attributes["runat"] = "server";
UP_AmountToBuy.ContentTemplateContainer.Controls.Add(newLBL);
row.Cells[0].Controls.Add(UP_AmountToBuy);
count++;
}
}
}
public void TB_AmountToBuy_TextChanged(object sender, EventArgs e)
{
((sender as TextBox).Parent.Controls[1] as Label).Text = (sender as TextBox).Text;
}
}

Try this, since you are using UpdatePanel. So use following property.
Set property:
EnableViewstate="True"

Related

Click event of dynamically created Button not firing

I'm creating dynamically generated buttons, and when I click on the button, the Add_Click method doesn't get fired up.
Here is a sample from my code:
protected void SearchRec(object sender, EventArgs e)
{
SearchResultsPanel.Controls.Clear();
string text_to_search = SearchTB.Text;
Friends RecToSearch = new Friends();
List<Friends> ListNFU = DBS.getNonFriendUsers(User.Identity.Name.ToString(), text_to_search);
if (ListNFU.Count != 0)
{
foreach (Friends NFRIndex in ListNFU)
{
string _FriendsOutput = FR_output(NFRIndex);
HyperLink RecHyperLink = new HyperLink();
RecHyperLink.Text = _FriendsOutput;
RecHyperLink.CssClass = "HyperLinkFriends";
RecHyperLink.ID = NFRIndex.UdName;
SearchResultsPanel.Controls.Add(new LiteralControl("<div style='height:32px'>"));
SearchResultsPanel.Controls.Add(RecHyperLink);
Button addUser = new Button();
addUser.CssClass = "ApproveBTN";
addUser.Text = "send";
addUser.Click += new EventHandler(Add_Click);
addUser.ID = NFRIndex.UdName + "3";
SearchResultsPanel.Controls.Add(addUser);
}
}
else
{
Label NoResultsLabel = new Label();
NoResultsLabel.Text = "Nothing is found";
SearchResultsPanel.Controls.Add(NoResultsLabel);
}
SearchResultsPanel.Controls.Add(new LiteralControl("</div>"));
}
private void Add_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string _tempID = btn.ID;
string id = _tempID.Substring(0, _tempID.LastIndexOf('3'));
DateTime cdate = new DateTime();
cdate = DateTime.Now;
DBS.AddFriend(User.Identity.Name, id, cdate);
btn.Visible = false;
btn.NamingContainer.FindControl(id).Visible = false;
}
Note: I did something very similar on page_load and it does work.
That is because when the page is reloaded, the control is most probably not recreated. That means that the event won't fire indeed.
You need to place this kind of code in the Page_Load so it gets recreated at postback.

Dynamically added button is not firing event and is losing state dispite re-adding it in pre_init event

I have a dropdown which is bound to a database. On its index change there is a function that add some button in a panel based upon selected value.
I am reading those button in page_init event but still I get null values, i.e. event bound with the button never fires.
Here is my code and dropdownlist1 is the dropdown that is adding dynamic button.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
colorgroupsTableAdapters.master_color_groupTableAdapter ta
= new colorgroupsTableAdapters.master_color_groupTableAdapter();
DataTable dt = ta.GetData();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = dt.Columns[1].ToString();
DropDownList1.DataValueField = dt.Columns[0].ToString();
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select One", "0"));
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
bindcolors();
}
}
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
}
protected void DropDownList2_DataBound(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex < 1)
{
DropDownList2.Items.Clear();
}
DropDownList2.Items.Insert(0, new ListItem("Select One", "0"));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["dd"] = DropDownList1.SelectedIndex;
bindcolors();
}
void bindcolors()
{
if (DropDownList1.SelectedIndex > 0)
{
addcolorgroupsTableAdapters.groupavailablecolorTableAdapter ta
= new addcolorgroupsTableAdapters.groupavailablecolorTableAdapter();
DataTable dt = ta.GetData(int.Parse(DropDownList1.SelectedValue));
HtmlTable ht = new HtmlTable();
ht.Width = "90%";
ht.Border = 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell tc1 = new HtmlTableCell();
HtmlTableCell tc2 = new HtmlTableCell();
HtmlTableCell tc3 = new HtmlTableCell();
object[] ob = dt.Rows[i].ItemArray;
tc1.InnerHtml = ob[0].ToString();
tc2.InnerHtml = ob[1].ToString();
tc2.BgColor = "#" + ob[1].ToString();
Button b = new Button();
b.Text = "Remove";
b.CommandArgument = ob[0].ToString();
AjaxControlToolkit.ConfirmButtonExtender cb
= new AjaxControlToolkit.ConfirmButtonExtender();
cb.ConfirmText = "Are You Sure To Delete This Color From The Group?";
b.ID = "Bo" + ob[0].ToString();
b.EnableViewState = true;
b.Click += new EventHandler(b_Click);
cb.TargetControlID = "Bo" + ob[0].ToString();
tc3.Controls.Add(b);
tc3.Controls.Add(cb);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tr.Cells.Add(tc3);
ht.Rows.Add(tr);
}
Panel1.Controls.Add(ht);
}
}
void b_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
int grp = int.Parse(DropDownList1.SelectedValue);
int clid = int.Parse(b.CommandArgument);
addcolorgroupsTableAdapters.QueriesTableAdapter ta
= new addcolorgroupsTableAdapters.QueriesTableAdapter();
ta.DeleteQuery_group_color(grp, clid);
DropDownList2.DataBind();
bindcolors();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex > 0 && DropDownList2.SelectedIndex > 0)
{
int grp = int.Parse(DropDownList1.SelectedValue);
int clid = int.Parse(DropDownList2.SelectedValue);
addcolorgroupsTableAdapters.QueriesTableAdapter ta
= new addcolorgroupsTableAdapters.QueriesTableAdapter();
ta.Insert_into_group_color(grp, clid);
DropDownList2.DataBind();
bindcolors();
}
}
Please tell what I am doing wrong?
I think the problem is the check for SelectedIndex > 0 in bindControls. The reason is that ViewState is evaluated between the Init and Load so the value for the SelectedIndex property is not set yet (and therefore = -1).
You could try a different approach: use a Repeater control that is databound to the results of the database query. This way, the general structure can be defined in the Repeater and its ItemTemplate. Also the EventHandlers are registered in the ItemTemplate.
You can reset the DataSource of the Repeater whenever the SelectedIndex of the Combobox changes and do not need to recreate the controls dynamically in init.
Your code should be much shorter and behave more deterministic.

Event Handler function is called only once and not the second Time

I have a web page with multiple Drop Down list created at run time using Template fiels in GridView.
I have assigned event handler to DDL on selectedindexchange event.
But this event handler function is getting called only once and my gridview is getting updated only once.
How do I make my event handler function be called after every selection index change.
Here is MY Code
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("empName"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Insert(y, linkF);
y++;
}
else if (coloumn.ColumnName.Equals("empName"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Insert(y, bfield);
y++;
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa,String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "",conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
}
Mu Event Handler function dp_selected is called only Once. I have called my GridBind() function in Page_Load().
Any help would be highly appreciated.
Thanks in Advance

GridView RowCommand Events not firing when button created with an external class

Ok The problem is I have a grid that I need to have paging on it with pages shown as numbers
I want to add two link button to the paging section to alow user to navigate to next page prev page
Here is my code
protected void CustomerGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
var grid = sender as GridView
if (e.Row.RowType == DataControlRowType.Pager)
{
var prvLink = new LinkButton();
prvLink.Text = "<";
prvLink.CommandName = "Page";
prvLink.CommandArgument = "Prev";
prvLink.EnableViewState = true;
var nextLink = new LinkButton();
nextLink.Text = ">";
nextLink.CommandName = "Page";
nextLink.CommandArgument = "Next";
nextLink.EnableViewState = true;
var prvCell = new TableCell();
var nextCell = new TableCell();
prvCell.Controls.Add(prvLink);
nextCell.Controls.Add(nextLink);
Table pagerTable = e.Row.Controls[0].Controls[0] as Table;
TableRow row = pagerTable.Rows[0];
row.Cells.AddAt(0, prvCell);
row.Cells.AddAt(row.Cells.Count, nextCell);
if (grid.PageIndex == 0)
{
prvCell.Enabled = false;
}
if (grid.PageIndex == grid.PageCount - 1)
{
nextCell.Enabled = false;
}
}
}
its perfectly working and users are able to navigate back and forward (and I can see grid RowCommand event getting fired)
The problem is I do not want to put the code inside my page (to make my page tiny and put the responsibility to an other class )
here is my class
public class GridStyler
{
private GridView _grid;
public GridStyler(GridView grid)
{
_grid = grid;
}
public void AddNextPreviousOnPager()
{
_grid.RowCreated += _grid_RowCreated;
}
void _grid_RowCreated(object sender, GridViewRowEventArgs e)
{
var grid = sender as GridView;
if (e.Row.RowType == DataControlRowType.Pager)
{
var prvLink = new LinkButton();
prvLink.Text = "<";
prvLink.CommandName = "Page";
prvLink.CommandArgument = "Prev";
prvLink.EnableViewState = true;
var nextLink = new LinkButton();
nextLink.Text = ">";
nextLink.CommandName = "Page";
nextLink.CommandArgument = "Next";
nextLink.EnableViewState = true;
var prvCell = new TableCell();
var nextCell = new TableCell();
prvCell.Controls.Add(prvLink);
nextCell.Controls.Add(nextLink);
Table pagerTable = e.Row.Controls[0].Controls[0] as Table;
TableRow row = pagerTable.Rows[0];
row.Cells.AddAt(0, prvCell);
row.Cells.AddAt(row.Cells.Count, nextCell);
if (grid.PageIndex == 0)
{
prvCell.Enabled = false;
}
if (grid.PageIndex == grid.PageCount - 1)
{
nextCell.Enabled = false;
}
}
}
}
then I should be able to call a code like that in my page load and it should create the link buttons and response to click of them
var g = new GridStyler(CustomerGridView);
g.AddNextPreviousOnPager();
what happens is the link buttons are created just fine but when user clicks them page get refreshed but RowCommand never get fired (they get fired of course when user clicks other buttons but not this two dynamically created buttons)
Any suggestion is really appreciated

Event won't fire in webpart lifecycle

I have a webpart that is quire simple. CLick on "Add" link that sets a 2 text boxes visible. Type in some text and click "Save" button but the click event won't fire. I'm pasting the code it hopes of some suggestion. I've searched for solutions but haven't found anything I can go on. I realize what maight be the issue but don't know how to corrct it. I need to be able to wireup and event with the handler sotimes before the page renders and I tried to override the OnPreRender method but it did not work in right moment.
Other minor issue that I will need to address is that the onFocus method doesn't work in txtMyLinkName.Focus(). Thanks for your help! - Risho
public class MyLinks : WebPart
{
public static string m_Portal = ConfigurationManager.ConnectionStrings["dbPortal"].ConnectionString;
Panel pnlMyLinks = new Panel();
Label lblError = new Label();
Label lblMyLinkURL = new Label();
Label lblMyLinkName = new Label();
TextBox txtMyLinkName = new TextBox();
TextBox txtMyLinkURL = new TextBox();
Button btnSaveMyLink = new Button();
LinkButton lbMyLinkAdd = new LinkButton();
Literal litP1 = new Literal();
Literal litBR1 = new Literal();
public cisf_MyLinks()
{
this.Title = "MyLinks";
this.ExportMode = WebPartExportMode.All;
}
protected override void CreateChildControls()
{
GetLinks();
base.CreateChildControls();
}
//protected override void OnPreRender(EventArgs e)
//{
// btnSaveMyLink.Text = "Save";
// btnSaveMyLink.Click += new EventHandler(btnSaveMyLink_Click);
// Controls.Add(btnSaveMyLink);
// base.OnPreRender(e);
//}
protected void GetLinks()
{
pnlMyLinks.Controls.Clear();
int i = 0;
lbMyLinkAdd.Text = "Add";
pnlMyLinks.Controls.Add(lbMyLinkAdd);
lbMyLinkAdd.Click += new EventHandler(lbMyLinkAdd_Click);
pnlMyLinks.Controls.Add(new LiteralControl("<br />"));
IDataReader drMyLinks = Get_MyLinks(Page.Request.ServerVariables["Logon_User"].Split("\\".ToCharArray())[1].ToLower());
while (drMyLinks.Read())
{
HyperLink hlMyLink = new HyperLink();
LinkButton lbDelMyLink = new LinkButton();
lbDelMyLink.Text = "(del)";
lbDelMyLink.ToolTip = "Delete this link";
lbDelMyLink.CssClass = "verytiny";
lbDelMyLink.Command += new CommandEventHandler(DelMyLink);
lbDelMyLink.CommandName = drMyLinks["id"].ToString();
pnlMyLinks.Controls.Add(lbDelMyLink);
pnlMyLinks.Controls.Add(new LiteralControl(" "));
hlMyLink.ID = "hl" + drMyLinks["ID"].ToString();
hlMyLink.Text = drMyLinks["Title"].ToString();
hlMyLink.NavigateUrl = drMyLinks["url"].ToString();
hlMyLink.Target = "_blank";
hlMyLink.ToolTip = drMyLinks["Title"].ToString();
pnlMyLinks.Controls.Add(hlMyLink);
pnlMyLinks.Controls.Add(new LiteralControl("<br />"));
if (drMyLinks["ID"].ToString() != "") { i += 1; }
}
this.Controls.Add(pnlMyLinks);
}
protected void lbMyLinkAdd_Click(object sender, EventArgs e)
{
lbMyLinkAdd.Visible = false;
lblMyLinkName.Visible = true;
txtMyLinkName.Visible = true;
litBR1.Visible = true;
lblMyLinkURL.Visible = true;
txtMyLinkURL.Visible = true;
btnSaveMyLink.Visible = true;
litP1.Visible = true;
(txtMyLinkName - dot focus)
lblMyLinkName.Text = "Link Name: ";
lblMyLinkURL.Text = "Link URL: ";
btnSaveMyLink.Text = "Save";
btnSaveMyLink.Click += new EventHandler(btnSaveMyLink_Click);
pnlMyLinks.Controls.Add(new LiteralControl("<table class='mylinksTable' cellpadding='0' cellspacing='0' border='1'><tr valign='top'><td>"));
pnlMyLinks.Controls.Add(lblMyLinkName);
pnlMyLinks.Controls.Add(new LiteralControl("</td><td>"));
pnlMyLinks.Controls.Add(txtMyLinkName);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr><tr valign='top'><td>"));
pnlMyLinks.Controls.Add(lblMyLinkURL);
pnlMyLinks.Controls.Add(new LiteralControl("</td><td>"));
pnlMyLinks.Controls.Add(txtMyLinkURL);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr><tr valign='top'><td colspan='2'>"));
pnlMyLinks.Controls.Add(btnSaveMyLink);
pnlMyLinks.Controls.Add(new LiteralControl("</td></tr></table>"));
this.Controls.Add(pnlMyLinks);
}
protected void btnSaveMyLink_Click(object sender, EventArgs e)
{
string thisURL;
if ((txtMyLinkName.Text != "") && (txtMyLinkURL.Text != ""))
{
if (txtMyLinkURL.Text.StartsWith("http"))
{ thisURL = txtMyLinkURL.Text; }
else { thisURL = "http://" + txtMyLinkURL.Text; }
AddMyLink(txtMyLinkName.Text, thisURL, Page.Request.ServerVariables["Logon_User"].Split("\\".ToCharArray())[1].ToLower());
GetLinks();
txtMyLinkName.Text = "";
txtMyLinkURL.Text = "";
lbMyLinkAdd.Visible = true;
}
lbMyLinkAdd.Visible = true;
lblMyLinkName.Visible = false;
txtMyLinkName.Visible = false;
litBR1.Visible = false;
lblMyLinkURL.Visible = false;
txtMyLinkURL.Visible = false;
btnSaveMyLink.Visible = false;
litP1.Visible = false;
}
}
If you are creating the button in code, then it needs to be wired up in the Page_Load event so that the click event can fire. Page_PreRender is too late.
In addition to adding the control in Load event as already posted, you should set the ID field e.g. btnSaveMyLink.ID = "SaveLink"; to a unique value.

Categories

Resources