dynamic columns disappears after postback - asp.net

I have a GridView with some BoundFields and two TemplateFields. In these two TemplateFields, I dynamically create UserControls containing a DropDownList and a TextBox, which users can modify.
When I try to get the values of the controls after a PostBack, the values in BoundFields are still there but my dynamic controls disappears. I can create them again but it won't get the user's values... How can I get these values before they're lost?
Here's some of my code:
In the RowDataBound event:
Select Case type
Case "BooleanBis"
e.Row.Cells(2).Controls.Clear()
Dim list1 As BooleanBisList = New BooleanBisList(avant, False)
e.Row.Cells(2).Controls.Add(list1)
e.Row.Cells(4).Controls.Clear()
Dim list2 As BooleanBisList = New BooleanBisList(apres, True)
e.Row.Cells(4).Controls.Add(list2)
Case "Boolean"
e.Row.Cells(2).Controls.Clear()
Dim list3 As BooleanList = New BooleanList(avant, False)
e.Row.Cells(2).Controls.Add(list3)
e.Row.Cells(4).Controls.Clear()
Dim list4 As BooleanList = New BooleanList(apres, True)
e.Row.Cells(4).Controls.Add(list4)
End Select
In my button click event, I try to get the user control :
Case "String"
temp.ChampValeurApres = DirectCast(Tableau1.Rows(i).Cells(selectedColumn).Controls(1), TextBox).Text
but i get the error that it doesn't exist.

You should create dynamic controls in RowCreated instead of RowDataBound because this event gets fired on every postback whereas RowDataBound only will fire when the GridView gets databound to it's DataSource.
Dynamically created controls must be recreated on every postback with the same ID as before, then they retain their values in the ViewState and events will fire correctly(f.e. a DropDownList's SelectedIndexChanged event).
So you should create them in RowCreated and "fill" them in RowDataBound(f.e. the DropDownList datasource/Items or a TextBox-Text).

I had been using:
EnableViewState="false"
in the GridView attributes. Removing it solved my problem!

I just did
protected void Page_Load(object sender, EventArgs e)
{
if (!(Page.IsPostBack))
{
// Put the selected items which u want to keep on postback
}
else
{
//regenerate auto created controls
}
}
and it worked as well

Related

DropDownList - Retrieving Data from Database - Disappear After AutoPostBack

My DropDownList1 retrieves a data from a column in the database, on the same page, I have another DropDownList2 that when Selecting a value, it will fire an AutoPostBack, the problem I am running into is,
if I select a value from DropDownList1, the value will be un-selected when the AutoPostBack happens, how can I make the DropDownList keeps the selected Value when an AutoPostBack is fired?
Thank you
You must be binding the DropDownList1 in Page_Load event. in that case, you should make sure that you should bind it only for first time and not every time by using IsPostBack property like below, otherwise every time it will get data from DB and will re-populate your dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
If(!IsPostBack)
{
//Bind DropDownList1
}
}
Ensure the viewstate is set to True so the values stored in the dropdown get reset from the viewstate, as well as the control's selected value.

Dynamically added link button disappeared on button click leaving an empty column

The datagrid reads from several xml files, so I create the columns dynamically, and added a templatefield as the last column.
A link button is added in the templatefield using RowDataBound.
Private Sub GridItem_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridItem.RowDataBound
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim linkb As New LinkButton
linkb.Text = "Delete"
linkb.ID = "LinkDeleteItem"
linkb.OnClientClick = "javascript:DeleteItem('" & Convert.ToString(e.Row.RowIndex) & "')"
e.Row.Cells(GridItem.Columns.Count - 1).Controls.Add(linkb)
End If
Catch ex As Exception
lblMessage.Text = ex.Message
End Try
End Sub
Everything works fine.
But when I click a button outside the gridview, to open a window to add a new item to the grid, the linkbuttons disappear. But the column is still there.
If I just close the new window without saving a new data (which will prompt the grid to rebind), the column remains empty. I had to reload the gridview for the linkbuttons to appear.
Is it because the linkbuttons are created on rowdatabound? How should I solve this?
This is happening because the OnRowDataBound event of GridView is NOT called on next postback. This happens because by default viewstate of GridView is set true i.e. EnableViewState property of Gridview is true. When ViewState is on, Gridview stores data from the same and OnRowDataBound event is not called. Also, at this point View state will not be applied for your linkButtons as they aren't created in page_load.
Try setting EnableViewState property to false for your gridview:
<asp:GridView ID="CustomersGridView"
OnRowDataBound="CustomersGridView_RowDataBound"
EnableViewState="false"
.... />
OR you can also bind your GridView in page_Load as:
protected void Page_Load(object sender, EventArgs e)
{
CustomersGrIdView.DataBind();
}
Now after every postback your OnRowDataBound event will be called and hence the LinkButtons will be available everytime.
NOTE: Setting EnableViewState property to false for gridview can be a bad practice to an extent, especially in scenarios of heavy data usages. Same goes for Binding gridview every time.
When using dynamic controls, they exist only until the next postback.ASP.NET will not re-create a dynamically added control. If you need to re-create a control next time too on postback, you should perform the control creation in the PageLoad event handler.
This will give you benefit of using view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the PageLoad event, ASP.NET will apply any view state information that it has after the PageLoad event handler ends.

How to get values from Controls which are in GridView?

I am new to asp.net website developer.
In my website I use GridView Control.In the GridView row i place some controls like
TextBox,DropDownList.
I can display the values in GridView.
But my requirement is ,Get the values from TextBox and DropdownList Which are existed in GridView.
Please help me to go forward..
thank you,
bye..
You need to access them by row. This code project article explains it in detail.
TextBox tb = (TextBox)gridview1.Rows[0].FindControl("idOfTextBox");
It above statement will find control in the first row of grid which has id idOfTextBox and type is textbox.
You can directly get any value of any control by casting directly, without using an extra textbox or dropdown variable.
Example:
string val = ((TextBox)gridview1.Rows[0].FindControl("TextBox_ID")).Text;
Hope it helps :)
Subscribe the RowDataBound event(this will be fired on each row available in gridview) of gridview and access like stated below,
protected void grdBillingdata_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//these controls are available inside gridview
HiddenField hdnNagetiveAmt = (HiddenField)e.Row.FindControl("hdnNagetiveAmt");
DropDownList ddlFeeType = (DropDownList)e.Row.FindControl("ddlFeeType");
TextBox txtFeeDesc = (TextBox)e.Row.FindControl("txtFeeDesc");
Button btnUpdate = (Button)e.Row.FindControl("btnUpdate");
}
}
not only text box we can get values from all the controls that used inside gridview that placed by using itemTemplate or simply a Bound field .
you need to loop for each row to get the values
foreach (GridViewRow row in grd_popup_details.Rows)
{
//get control values
}
Refference link

How can I find the RepeaterItem I have clicked?

I am creating a simple ASP page that has a Repeater control. This repeater control contains LinkButtons; so that as the repeater increases in item size, the amount of LinkButtons also increases. My question is, how can I identify uniquely the RepeaterItem to which I click the LinkButton?.
I though of using a Foreach to search through the RepeaterItems but I don't know what conditions should I use to identify the Linkbutton I cliked. By the way, each LinkButton have the same name and same ID.
My goal is to get the RepeaterItem in which that Linkbutton belongs
Thanks,
Y_Y
Assign Command/ComandArgument for your LinkButton
Assign handler 'OnCommand' for your Repeater and create event handler
In the handler you get RepeaterCommandEventArgs - use item property to access
You can use:
- Tag property of LinkButton to store object to identify the LinkButton
- Included hidden field in Repeater template to store something to identify Linkbutton.
- Using CommandArgument of LinkButton
- ...
You can look at using what is called "ItemCommand"
or you can set the CommandArgument of your LinkButton.
protected void lnkButton_Click(object sender, EventArgs e) {
LinkButton _sender = (LinkButton)sender;
string argument = _sender.CommandArgument;
}
The common solution for this scenario is to use the CommandName and/or CommandArgument properties of the button. Just bind the CommandArgument to the ID of the objects you put into the repeater. The command argument can be accessed in the click handler.

Should a DropDownList within a CompositeControl remember selected item?

Given the following
public class MyControl : CompositeControl
{
private DropDownList myList;
protected override void CreateChildControls()
{
base.CreateChildControls();
myList = new DropDownList();
myList.AutoPostBack = true;
this.Controls.Add(myList);
if (!Page.IsPostBack)
{
myList.DataSource = MyBLL.SomeCollectionOfItems;
myList.DataBind();
}
}
}
I find that the items in the list persist properly, but when a different control is rendered and then this one is rendered again, the last selected item is not persisted. (The first item in the list is always selected instead)
Should the last selected item be persisted in ViewState automatically, or am I expecting too much?
I think this is a hidden ViewState issue. You create and bind a control in CreateChildControls. You should only create the control at this place. Move the binding code to the classes load event and use EnsureChildControls.
Here is the solution which is best recommended. It lies in understandng the Page Life Cycle correctly!! Postback Controls like Drop Down List restore their posted state (the selected item of a Drop Down List posted). It forgets its selected value because you are rebinding it in Page_Load event, which is after the Drop Down List has been loaded with posted value (because View State is loaded after Page_Init event and before Page_Load event). And in this rebinding in Page_Load event, the Drop Down List forgets its restored selected item. The best solution is to perform the Data Binding in the Page_Init event instead of Page_Load event.
Do something like the below...
Suppose Drop Down List name is lstStates.
protected void Page_Init(object sender, EventArgs e)
{
lstStates.DataSource = QueryDatabase(); //Just an example.
lstStates.DataTextField = "StateName";
lstStates.DataValueField = "StateCode";
lstStates.DataBind();
}
ASP.NET loads control's View State after Page_Init event and before Page_Load event, so Drop Down List's selectedIndex will not be affected, and you will get desired results magically!!

Resources