Dynamic ImageButton click event not fired - c#

I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
using (ImageButton _btnRemoveEmpleado = new ImageButton())
{
_btnRemoveEmpleado.ID = "btnOffice_1";
_btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
_btnRemoveEmpleado.Height = 15;
_btnRemoveEmpleado.Width = 15;
_btnRemoveEmpleado.ImageUrl = "cross-icon.png";
_btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);
this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
}
}
void _btnRemoveEmpleado_Click(object sender, ImageClickEventArgs e)
{
try
{
string s = "";
}
catch (Exception ex)
{
}
finally { }
}
When I click on _btnRemoveEmpleado, the postback is executed but I never reach the string s = ""; line. How could I execute the _btnRemoveEmpleado_Click code, please?

Remove the using, controls are disposed automatically by ASP.NET, they have to live until the end of the page's lifecycle. Apart from that create your dynamic control in Page_Init, then it should work.
protected void Page_Init(object sender, EventArgs e)
{
ImageButton _btnRemoveEmpleado = new ImageButton();
_btnRemoveEmpleado.ID = "btnOffice_1";
_btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
_btnRemoveEmpleado.Height = 15;
_btnRemoveEmpleado.Width = 15;
_btnRemoveEmpleado.ImageUrl = "cross-icon.png";
_btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);
this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
}

Related

I have the following error when I use DropDownlist for 3rd or second time! "failed to load viewstate is being loaded must .."

I have a "listview" for showing list of employee and a "dropdownlist" to select department. The following error occurs when I use "DropDownlist" for 3rd or second time:
"Failed to load viewstate".
The control tree into which viewstate is being loaded must match the control tree that was used to save "viewstate" during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request."
This is asp.net Webform and I have to use this technology and have no other choice .
namespace .Presentation.general
{
public partial class Listg : PageBase
{
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/App_MasterPages/empty.Master";
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDepartmentsDropDownList();
GeneralObjectDataSource.SelectParameters["Department"].DefaultValue = "";
decimal presence = Convert.ToDecimal(Data.EmployeeDB.Create().GetCountEMPOnlineToday());
decimal visibles = Convert.ToDecimal(Data.EmployeeDB.Create().GetCountVisiblesEmployees());
visibles = (visibles == 0 ? 1 : visibles);
PresenceLabel.Text = System.Math.Round((presence / visibles) * 100, 1).ToString() + "% " + string.Format(" ({0})", presence);
}
}
public void Search(object sender, EventArgs e)
{
GeneralObjectDataSource.SelectParameters["name"].DefaultValue = Common.Converter.ConvertToFarsiYK(NameTextBox.Text.Trim());
if (PresenceRadioBottonList.SelectedValue == "1")
{
GeneralObjectDataSource.SelectParameters["onlyPresence"].DefaultValue = "true";
}
else
{
GeneralObjectDataSource.SelectParameters["onlyPresence"].DefaultValue = "false";
}
DataListView.DataBind();
}
public void select_department_SelectedIndexChanged(object sender, EventArgs e)
{
GeneralObjectDataSource.SelectParameters["name"].DefaultValue = "";
GeneralObjectDataSource.SelectParameters["Department"].DefaultValue = select_department.SelectedItem.Text;
GeneralObjectDataSource.DataBind();
DataListView.DataBind();
}
private void PopulateDepartmentsDropDownList()
{
select_department.DataSource = Biz.EmployeeBO.GetDepartments();
select_department.DataTextField = "Name";
select_department.DataValueField = "ID";
select_department.DataBind();
select_department.Items.Insert(0, new ListItem("", "0"));
select_department.SelectedValue = Biz.Settings.SelectedDepartmentID;
}
}
}

Rows adding as many times as page refreshes

I am inserting some content in database on button click event every thing is working fine while insertion of the Data.
The problem is I just refreshed the page after the button click then I noticed that after the button click Data is inserting as many time as I refreshes the page.
How can I stop this ?
Here is my Button Code :
protected void btn_AddEdu_Click(object sender, EventArgs e)
{
hfTab.Value = "edu";
if (ValidateAddEdu())
{
emp_edu.InsertEdu(Session["empcd"].ToString(), ddl_degree.SelectedValue.ToString(), txt_eduterms.Text, ddl_institute.SelectedValue.ToString(), txt_edupassyear.Text, txt_edugrade.Text, ddl_sponsor.SelectedValue.ToString());
int imagefilelength = fileupload_edu.PostedFile.ContentLength;
byte[] imgarray = new byte[imagefilelength];
HttpPostedFile image = fileupload_edu.PostedFile;
image.InputStream.Read(imgarray, 0, imagefilelength);
edu_attach.InsertEduAttachment(Session["empcd"].ToString(),ddl_degree.SelectedValue.ToString(),imgarray);
lbl_eduerr.Text = "Added";
lbl_eduerr.ForeColor = System.Drawing.Color.Green;
BindEduGrid();
}
}
Add following code in your .cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
protected void btn_AddEdu_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
hfTab.Value = "edu";
if (ValidateAddEdu())
{
emp_edu.InsertEdu(Session["empcd"].ToString(), ddl_degree.SelectedValue.ToString(), txt_eduterms.Text, ddl_institute.SelectedValue.ToString(), txt_edupassyear.Text, txt_edugrade.Text, ddl_sponsor.SelectedValue.ToString());
int imagefilelength = fileupload_edu.PostedFile.ContentLength;
byte[] imgarray = new byte[imagefilelength];
HttpPostedFile image = fileupload_edu.PostedFile;
image.InputStream.Read(imgarray, 0, imagefilelength);
edu_attach.InsertEduAttachment(Session["empcd"].ToString(),ddl_degree.SelectedValue.ToString(),imgarray);
lbl_eduerr.Text = "Added";
//Add this line
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
lbl_eduerr.ForeColor = System.Drawing.Color.Green;
BindEduGrid();
}
}
}

UserControl Click event not firing

Hi this is my aspx page loading some values to the user control
protected void Page_Load(object sender, EventArgs e)
{
}
this is the usercontrol where i am loading and sending the values in find click event
protected void BtnFind_Click(object sender, EventArgs e)
{
Usr_BPOP BPOP = (Usr_BPOP)Page.LoadControl("~/Usr_BPOP.ascx");
BPOP.Date = txtDate.Text.Trim();
BPOP.DocNo = txtDocNo.Text.Trim();
BPOP.Code = txtCode.Text.Trim();
BPOP.Name = txtName.Text.Trim();
BPOP.Partcode = txtPartNo.Text.Trim();
if (chkReprint.Checked)
{
BPOP.BtnReprintVisible = true;
BPOP.BtnSaveVisible = false;
}
divControls.Controls.Clear();
PlaceHolder1.Controls.Add(BPOP);
}
this is my Usr_BPOP.ascx:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnReprint.Click += new EventHandler(btnReprint_Click);
}
btnReprint.Visible = false;
btnSave.Visible = BtnSaveVisible;
btnReprint.Visible = BtnReprintVisible;
if (btnReprint.Visible == false)
{
btnReprint.Text = "Print";
btnReprint.Visible = true;
}
table = new DataTable();
table.Columns.Add("DocNum", typeof(string));
table.Columns.Add("DocEntry", typeof(string));
table.Columns.Add("LineNum", typeof(string));
table.Columns.Add("PartNo", typeof(string));
table.Columns.Add("ItemDesc", typeof(string));
table.Columns.Add("QTR", typeof(string));
table.Columns.Add("QTP", typeof(string));
table.Columns.Add("Chk", typeof(bool));
table.Columns.Add("BarCode", typeof(string));
Datalayer dl = new Datalayer();
DataTable dttable = new DataTable();
if (!BtnSaveVisible && BtnReprintVisible)
BtnSaveVisible = true;
dttable = dl.GetPOItem(date, docNo, code, name, partcode, BtnReprintVisible, !BtnSaveVisible).Tables[0];
foreach (DataRow dr in dttable.Rows)
{
table.Rows.Add(dr["DocNum"].ToString(), dr["DocEntry"].ToString(), dr["LineNum"].ToString(), dr["PartNo"].ToString(),
dr["ItemDesc"].ToString(), dr["QTR"].ToString(), dr["QTP"].ToString(), Convert.ToBoolean(dr["Chk"]), dr["Barcode"].ToString());
}
if (table != null && table.Rows.Count > 0)
{
grdlistofitems.DataSource = table;
Session["Table"] = table;
grdlistofitems.DataBind();
}
else
{
}
}
this is the reprint button click event when i cilck this event it is not firing:
void btnReprint_Click(object sender, EventArgs e)
{
}
Since you are not setting the ID of the control, it is generated anew every time the control added to the page. The generated ID might not be the same, and therefore the sender of the event cannot be recognized. So first thing you should do is assign an ID explicitly:
Usr_BPOP BPOP = (Usr_BPOP)Page.LoadControl("~/Usr_BPOP.ascx");
BPOP.ID = "SomeID";
Secondly, assignment of the event handler should be done very time the control is created - that is, on every request, does not matter whether this is a postback or not - otherwise ASP.NET will not be able to determine what method should be called when the event is fired:
protected void Page_Load(object sender, EventArgs e)
{
// No check for postback here
btnReprint.Click += new EventHandler(btnReprint_Click);
Update. There is one more reason why this code does not behave as expected. The BPOP control is added to the page only on btnFind click. When the postback is caused by anything else, including btnReprint, on the response page generation BPOP control is not added to the page at all. If there is no control on the page - obviously its methods, including event handlers, cannot be triggered.
Here is quick and dirty fix for this situation. It should be applied to the page code where BPOP control is added:
protected void Page_Load(object sender, EventArgs e)
{
bool? addBPOP = ViewState["AddBPOP"] as bool?;
if (addBPOP.HasValue && addBPOP.Value)
{
AddBPOP();
}
}
protected void BtnFind_Click(object sender, EventArgs e)
{
AddBPOP();
ViewState["AddBPOP"] = true;
}
protected void AddBPOP()
{
Usr_BPOP BPOP = (Usr_BPOP)Page.LoadControl("~/Usr_BPOP.ascx");
BPOP.ID = "BPOPID";
BPOP.Date = txtDate.Text.Trim();
BPOP.DocNo = txtDocNo.Text.Trim();
BPOP.Code = txtCode.Text.Trim();
BPOP.Name = txtName.Text.Trim();
BPOP.Partcode = txtPartNo.Text.Trim();
if (chkReprint.Checked)
{
BPOP.BtnReprintVisible = true;
BPOP.BtnSaveVisible = false;
}
divControls.Controls.Clear();
PlaceHolder1.Controls.Add(BPOP);
}
Change:
void btnReprint_Click(object sender, EventArgs e)
{
}
To
protected void btnReprint_Click(object sender, EventArgs e)
{
}

Refresh listbox after adding

I have a listbox in C# and want it to refresh after I added a new item(which gets opened with a new form dialog)
Here is my code which doesn't work.
private void showAllItems()
{
itemList = Db.getAllItems();
lb_itemList.DataSource = itemList;
}
private void showItemPreview(object sender, EventArgs e)
{
string curItem = lb_itemList.SelectedItem.ToString();
briefPreviewList = Db.getItemBriefPreview(curItem);
string itemInfos = string.Join(",", briefPreviewList.ToArray());
string[] infos = itemInfos.Split(',');
l_itemDB.Text = curItem;
l_CategoryDB.Text = infos[0];
}
private void b_addItem_Click(object sender, EventArgs e)
{
int uid = 1;
AddItem addItemForm = new AddItem(uid);
addItemForm.ShowDialog();
CurrencyManager cm = (CurrencyManager)BindingContext[itemList];
cm.Refresh();
}
I assume when you insert a new item it gets stored into the database, if this is the case then all you need to do is reset the datasource:
private void b_addItem_Click(object sender, EventArgs e)
{
int uid = 1;
AddItem addItemForm = new AddItem(uid);
addItemForm.ShowDialog();
addItemForm.Dispose();
this.showAllItems();
}

Retrieving values of dynamically created controls on Post back in Asp.Net

I need to dynamically add CheckBoxList on the SelectedIndexChanged event of DropDownList. I have achieved this but I cannot retain its value on postback.
Here’s what I have done so far:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
loadTracks();//Needs to generated dynamically
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadDegrees();
}
loadTracks();
}
public void loadTracks()
{
try
{
ConfigurationDB objConfig = new ConfigurationDB();
DataSet ds = objConfig.GetTracksByDegreeID(
Convert.ToInt32(ddlDegree.SelectedValue.ToString()));
CheckBoxList CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
CbxList.Items.Add(new ListItem(ds.Tables[0].Rows[i]["Track_Name"]
.ToString(), ds.Tables[0].Rows[i]["ID"].ToString()));
}
ph.Controls.Add(CbxList);
ViewState["tracks"] = true;
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
//For testing, I added a button and on its click I have added this code
protected void btnDetails_Click(object sender, EventArgs e)
{
CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
foreach (ListItem ex in Cbx.Items)
{
if (ex.Selected)
{
Response.Write(String.Format("You selected: <i>{0}</i> <br>", ex.Value));
}
}
}
Might be a typo:
CbxList.ID = "Cbx";
v.s.
CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
You can try it without changing the code and use pre PreRender
just run you loadTracks()

Categories