why my function doesn't execute after clicking dynamically created button - asp.net

here is my scenarioton : if !page.Ispostback i fill a dropdown with data from database!
Also in the page there is a butron and onclick it gets one id from database and crates one panel IN WHIH THERE IS DYNAMICALLY CREATED BUTTON. The PROBLEM IS WHEN I CLICK THIS DYNAMICALLY CREATED BUTTON _ JUST NOTHING HAPPENS AND I CANT EXPLAIN WHY.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguages.DataSource = this.catRep.GetAllAvailableLanguages();
ddlLanguages.DataBind();
}
//IEnumerable<CatgoriesLanguages> allcategories = this.catRep.GetAllCategoriesByID(1)
}
protected void btnAddNew_Click(object sender, EventArgs e)
{
inseredID = this.catRep.AddCategory();
Label mylab = new Label();
mylab.Text = "Yeeee" + inseredID;
Page.FindControl("form1").Controls.Add(mylab);
Panel myFieldSet = new Panel();
myFieldSet.GroupingText= "Add New Category";
Label lblTitle = new Label();
lblTitle.Text="Title: ";
myFieldSet.Controls.Add(lblTitle);
TextBox txbTitle = new TextBox();
txbTitle.ID = "txbTitle";
myFieldSet.Controls.Add(txbTitle);
myFieldSet.Controls.Add(new LiteralControl("<br />"));
Label lblShrtDescrpt = new Label();
lblShrtDescrpt.Text = "Short Description: ";
myFieldSet.Controls.Add(lblShrtDescrpt);
TextBox txbShrtDescrpt = new TextBox();
txbShrtDescrpt.ID = "txbShrtDescrpt";
myFieldSet.Controls.Add(txbShrtDescrpt);
myFieldSet.Controls.Add(new LiteralControl("<br />"));
Label lblDescrpt = new Label();
lblDescrpt.Text = "Description: ";
myFieldSet.Controls.Add(lblDescrpt);
TextBox txbDescrpt = new TextBox();
txbDescrpt.ID = "txbDescrpt";
myFieldSet.Controls.Add(txbDescrpt);
Button btnAddcategorieslanguage = new Button();
btnAddcategorieslanguage.Click += new EventHandler(btnAddcategorieslanguage_Click);
myFieldSet.Controls.Add(btnAddcategorieslanguage);
Page.FindControl("form1").Controls.Add(myFieldSet);
}
public void btnAddcategorieslanguage_Click(object sender, EventArgs e)
{
TextBox txbTitle = (TextBox)FindControl("txbTitle");
TextBox txbShrtDescrpt = (TextBox)FindControl("txbShrtDescrpt");
TextBox txbDescrpt = (TextBox)FindControl("txbDescrpt");
this.catRep.AddCategoriesLanguages(11, 2, "malee", "tariiiiii", "liliiii");
}

You need to create all dynamically added controls in page Init or page load event too.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(ThereIsDynamicControl())
{
//You can set some session or viewState in the btnAddNew_Click to determine whether you need to add dynamic controls again here or not.
}
if (!IsPostBack)
{
ddlLanguages.DataSource = this.catRep.GetAllAvailableLanguages();
ddlLanguages.DataBind();
}
//IEnumerable<CatgoriesLanguages> allcategories = this.catRep.GetAllCategoriesByID(1);
}

Related

Asp.net Gridview row edit - How to remove select row event

Hi Friends wish you all Happy New Year 2017!
I am displaying records in grid and i have code to select the row and display records in text boxes as per selected row.
I have Edit Button to edit records in grid row but when i click on text box (edit mode) to enter value it is showing error because the "select row" event is still active.
Any help how to remove the select row action when edit button is clicked.
// click on the row to select and display records in text boxes
protected void gvUsrEdit_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvUsrEdit.SelectedRow;
Label l1 = row.FindControl("Label1") as Label;
Label l2 = row.FindControl("Label2") as Label;
i_TranInputID.Text = l1.Text;
tReason.Text = l11.Text;
gvUsrEdit.Visible = false;
}
protected void gvUsrEdit_RowEditing(object sender, GridViewEditEventArgs e)
{
gvUsrEdit.EditIndex = e.NewEditIndex;
show1();
}
public void show1()
{
string strquery = "select * from btaprs2 where vEmpID=#d1 and vQuarter=#d2 and vyear1=#d3 and tKRA=#d4 and v10='Active' ";
con.Open();
SqlCommand cmd = new SqlCommand(strquery, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUsrEdit.DataSource = ds;
gvUsrEdit.DataBind();
con.Close();
}
catch (Exception ex)
{
Response.Write(ex);
Label46.Text = "Error in page please check!";
}
}
You need to change the RowIndex.
protected void gvUsrEdit_RowEditing(object sender, GridViewEditEventArgs e)
{
gvUsrEdit.EditIndex = -1;
show1();
}
I would suggest to Edit the rows this way:
You may want to use RowUpdating method like this:
protected void gvUsrEdit_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
i_TranInputID.Text = ((Label)gvUsrEdit.Rows[e.RowIndex].FindControl("Label1") ).Text;
tReason.Text = ((Label)gvUsrEdit.Rows[e.RowIndex].FindControl("Label2")).Text;
tReason.Text = l11.Text;
gvUsrEdit.EditIndex = -1;
show1();
}

Wire up button created at runtime

Im creating some buttons based on a value of some runtime variable (i dont even know how many).
My code for the button is as follows:
Button cancel = new Button();
cancel.Text = "Cancel";
cancel.ID = "cancelEnrollmentForStudent" + zapsanePredmetyList.ElementAt(i).ID.ToString() + "-" + i ;
cancel.Click += new EventHandler(cancelEnrollment);
string toCancel = selectedSubject.SelectedValue + ";" + studentToEnroll.SelectedValue;
cancel.CommandArgument = toCancel;
while the code for the click method is
protected void cancelEnrollment(object sender, EventArgs e)
{
//do something when button clicked.
Button sourceButton = (Button)sender;
string[] data = sourceButton.CommandArgument.Split(';');
}
However, the click method is not firing up when the button is clicked. I suppose this has something to do with the fact, that I build the button at runtime. Cld someone advise on how to get this method fire up?
Thanks,
Ondrej
You have to override OnInit add the code in OnInit method.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Button btn = new Button();
btn.ID = "btn1";
btn.Text = "Button1";
btn.Click += new EventHandler(btn_Click);
this.form1.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
bt.Text = "Changed";
}

find a control by id from Dynamically added Template field in GridView

Hi i added template field dynamically to gridview by implementing ITemplate interface.
The template field contains some controls like label and textboxes. how do i get these controls in row databound event.
I am not able to get when i do gridviewrow.findcontrol("id") as i do normally when we add templatefield from aspx page.
The way i added template field is like this
public class CustomGridViewColumn : ITemplate
{
ListItemType _liType;
string _columnName;
public CustomGridViewColumn(ListItemType type, string column)
{
_liType = type;
_columnName = column;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_liType)
{
case ListItemType.Header:
Label lblHeader = new Label();
lblHeader.Text = _columnName;
container.Controls.Add(lblHeader);
break;
case ListItemType.Item:
Label lblItem = new Label();
lblItem.DataBinding += new EventHandler(lbl_DataBinding);
lblItem.ID = "lbl" + _columnName;
lblItem.ClientIDMode = ClientIDMode.Predictable;
container.Controls.Add(lblItem);
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(ddl_DataBinding);
ddl.ID = "ddl" + _columnName;
ddl.Visible = false;
container.Controls.Add(ddl);
break;
}
}
}
Now i want access the label and dropdown which i have added using this code.
when i do gridviewrow.findcontrol("id") i am not getting them.
Can any one please help me.
I am geeting when i go through all the rows and try to find but
i have a check box in a row when i select it all labels should diappear and ddls dhould appear
for this i am using the follwoing code.
protected void chkEdit_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkEditTest = (CheckBox)sender;
GridViewRow grow = (GridViewRow)chkEditTest.NamingContainer;
DropDownList ddl = (DropDownList)grow.FindControl("ddl");
Label lbl= (Label)grow.FindControl("lbl");
}
when i do this i am not able to get the controls.
it seems like controls are disapppearing on postback..
This is what I came up with and I can able to get the control reference in the code behind.
public class CustomGridViewColumn : ITemplate
{
ListItemType _liType; string _columnName;
public CustomGridViewColumn(ListItemType type, string column)
{
_liType = type;
_columnName = column;
}
void ITemplate.InstantiateIn(Control container)
{
switch (_liType)
{
case ListItemType.Header:
Label lblHeader = new Label();
lblHeader.Text = _columnName;
container.Controls.Add(lblHeader);
break;
case ListItemType.Item:
Label lblItem = new Label();
lblItem.DataBinding += new EventHandler(lblItem_DataBinding);
lblItem.ID = "lbl" + _columnName;
lblItem.ClientIDMode = ClientIDMode.Predictable;
container.Controls.Add(lblItem);
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(ddl_DataBinding);
ddl.ID = "ddl" + _columnName;
ddl.Visible = false;
ddl.DataSource = new string[] { "Hello", "World" };
container.Controls.Add(ddl);
break;
}
}
void ddl_DataBinding(object sender, EventArgs e)
{
}
void lblItem_DataBinding(object sender, EventArgs e)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
DataRow oItem = dt.NewRow();
oItem[0] = "Deepu";
dt.Rows.Add(oItem);
oItem = dt.NewRow();
oItem[0] = "MI";
dt.Rows.Add(oItem);
GridView gv = new GridView();
gv.ID = "myGridView";
gv.AutoGenerateColumns = false;
BoundField nameColumn = new BoundField();
nameColumn.DataField = "Name";
nameColumn.HeaderText = "Name";
gv.Columns.Add(nameColumn);
TemplateField TmpCol = new TemplateField();
TmpCol.HeaderText = "Template Column";
gv.Columns.Add(TmpCol);
TmpCol.ItemTemplate = new CustomGridViewColumn(ListItemType.Item, "TEST");
gv.DataSource = dt;
gv.DataBind();
Form.Controls.Add(gv);
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView gv = Form.FindControl("myGridView") as GridView;
foreach (GridViewRow item in gv.Rows)
{
var ddl = item.FindControl("ddlTest") as DropDownList;
if (ddl != null)
{
ddl.Visible = true;
}
var lbl = item.FindControl("lbl") as Label;
if (lbl != null)
{
lbl.Text = "hello";
}
}
}
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
Thanks
Deepu
Can you try using row index of GRIDVIEW control
var rowIndex = int.Parse(e.CommandArgument)
GridView1.Rows[rowIndex].FindControl("id")
Also refer
http://forums.asp.net/t/998368.aspx/1
http://www.codeproject.com/Articles/12021/Accessing-the-different-controls-inside-a-GridView
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.aspx
Thanks
Deepu

asp.net get the text from a dynamically inserted textbox return null all the time

I am writing a web app in asp.net, in one of my aspx pages I have a static table.
To this table I insert a dynamically textbox control from the code behind (from Page_Load, I create this control dynamically because I do not know if I need to create it or not it depend on a user answer), the problem is when i try to get the textbox text after the user click on a button, I tried every thing i know from Request.Form.Get("id of the control") to Page.FindControl("id of the control"), but nothing works I get null all the time, just to be clear the button that activate the function that get the text from the textbox is insert dynamically to.
Both button and textbox are "sitting" in a table and must remain so, I'd appreciate any help
my code is:
aspx page
<asp:Table ID="TabelMessages" runat="server"></asp:Table>
code behind aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.ID = "textBox";
tb.Text = "hello world";
TableCell tc = new TableCell();
tc.Controls.Add(tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
}
public void Button_Click(object o, EventArgs e)
{
string a = Request.Form.Get("textBox");//does not work
Control aa = Page.FindControl("textBox");//does not work
}
in your
public void Button_Click(object o, EventArgs e)
{
//try searching in the TableMessage.Controls()
}
Alternatively, and depending on what you ultimately want to do, and still use Page_Load:
In your Page Class:
protected TextBox _tb; //this is what makes it work...
protected void Page_Load(object sender, EventArgs e)
{
_tb = new TextBox();
_tb.ID = "textBox";
TableCell tc = new TableCell();
tc.Controls.Add(_tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
if (!Page.IsPostBack)
{
_tb.Text = "hello world";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = _tb.Text; //this will display the text in the TextBox
}
You need to run your code inside the Page_PreInit method. This is where you need to add / re-add any dynamically created controls in order for them to function properly.
See more information about these types of issues in the MSDN article on the ASP.NET Page Life Cycle.
Try changing your Page_Load code to the following:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
TextBox tb = new TextBox();
tb.ID = "textBox";
tb.Text = "hello world";
TableCell tc = new TableCell();
tc.Controls.Add(tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
}

Capture DropDownList Index Change event inside of grid View

I am trying to capture the SelectedIndexChanged event for a drop down list I have put inside of a gridview control. It posts back fine, but does not go into my SelectedIndexChanged event handler. Here is my code
DropDownList myddl;
protected void Page_Load(object sender, EventArgs e)
{
this.myGridview.RowDataBound += new GridViewRowEventHandler(myGridview_RowDataBound);
myddl = new DropDownList();
myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
if (!Page.IsPostBack)
{
List<Team> teams = giveMeTeams();
this.myGridview.DataSource = teams;
this.myGridview.AutoGenerateColumns = false;
BoundField col1 = new BoundField();
col1.DataField = "Name";
this.myGridview.Columns.Add(col1);
BoundField col2 = new BoundField();
col2.DataField = "Sport";
this.myGridview.Columns.Add(col2);
BoundField col3 = new BoundField();
col3.DataField = "Status";
this.myGridview.Columns.Add(col3);
this.myGridview.DataBind();
}
}
void myGridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
myddl = new DropDownList();
myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
List<string> items = new List<string>();
items.Add("good");
items.Add("bad");
myddl.DataSource = items;
myddl.AutoPostBack = true;
myddl.DataBind();
e.Row.Cells[2].Controls.Add(myddl);
}
void myddl_SelectedIndexChanged(object sender, EventArgs e)
{
string temp = "In Here"; //neve hits this code
}
private List<Team> giveMeTeams()
{
Teams teams = new Teams();
teams.Add(new Team("RedWings", "Hockey", "good"));
teams.Add(new Team("Lions", "Football", "bad"));
teams.Add(new Team("Packers", "Football", "good"));
return teams;
}
Any help is greatly appreciated.
Thanks,
Edited based on Comments
I have tried as you suggested...and am still not capturing the post back. here is my new code
void myGridview_RowCreated(object sender, GridViewRowEventArgs e)
{
DropDownList myddl = new DropDownList();
myddl = new DropDownList();
myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
myddl.ID = "MyID" + e.Row.RowIndex.ToString();
e.Row.Cells[2].Controls.Add(myddl);
}
void myGridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList myddl = e.Row.FindControl("MyID" + e.Row.RowIndex.ToString()) as DropDownList;
//myddl.SelectedIndexChanged += new EventHandler(myddl_SelectedIndexChanged);
List<string> items = new List<string>();
items.Add("good");
items.Add("bad");
myddl.DataSource = items;
myddl.DataMember = "Status";
myddl.AutoPostBack = true;
myddl.DataBind();
e.Row.Cells[2].Controls.Add(myddl);
}
it is still not going into my myddl_SelectedIndexChanged() eventhandler.
Create that Dropdownlist in RowCreated of the Grid and assign an ID to it. Get the refrence to these Dropdowns in RowDataBound via e.Row.FindControl("MyDropdownlistID") and bound them to the Datasource. Create distinct Dropdownlist instances instead of referencing always the same

Resources