Web User Control postback Issues - c#

I am new to ASP.net thing, and i have some question regarding postback.
I have a Senario like this:
1) I have a grid on web with a panel inside.
2) I "Insert" the panel with a Web User Control by calling this
Control ctlControl;
ctlControl = LoadControl("~/UserControls/ChequeCreation.ascx");
pnlTransaction.Controls.Add(ctlControl);
3)The Web User Control providing two button. One is "update" and one is "reset".
Problem is like here:
What i wanted to achieve is when press the "update" button, it will update something back to my DB? But seem after i press the button "Update" or "Reset". The web user control is gone or missing. For my guest is because of the postback issues? Is that correct?
I tried if(!postback) still its doesn't work.
How am i going to overcome this? I already scratching my head about a day?
Thanks you so much.
Regards
LiangCk:
PS:Sorry for my english level, and please dont hesitate to voice out my error or mistake.

well you can convert any of your data columns to template column and then drag and drop your web user control to it
this will result in something like the following code check where "uc1:webUserControle1" is located in the code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDB">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
<uc1:webUserControle1 ID="WebUserControle1_1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
</Columns>
</asp:GridView>

if you are using AJAX, try add updatepanel on your UCT design page

ASP.NET will not preserve a dynamically added user control between postbacks. This is why it is dissapearing. You will need to add the control each time the page is created. However you will need to add it when the control tree is being initialized and restore the original control ID if you want your events to fire. These links provide a full explanation https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx and http://avinashsing.sunkur.com/2011/02/24/dynamic-controls-viewstate-and-postback/

You have to Every Time Reload the user control on Page_Init or
Page_Load. Then you can get the Button Click Event and After tha User
Control will not lost.
private void LoadUserControl(){
string controlPath = LastLoadedControl;
if (!string.IsNullOrEmpty(controlPath)) {
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);
}
}
protected void Page_Load(object sender, EventArgs e) {
LoadUserControl();
}

Related

Gridview Select button no longer works after adding delete button

Ever since I added the Delete button, the Select button no longer redirects to another page when clicked. I added an alert on the OnSelectedIndexChanged and that worked so I am not sure why it no longer redirects. Also, if I remove the delete button the redirect works but I need both buttons.
<asp:CommandField ButtonType="Button" ShowSelectButton="True"></asp:CommandField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDeleteRecord" runat="server" Text="Delete" CommandName="Delete"
OnClientClick="return confirm('Are you sure you want to delete this item?');" />
</ItemTemplate>
</asp:TemplateField>
OnSelectedIndexChanged. If I removed false it didn't matter either.
protected void listIndexView_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("mypage.aspx", false);
}
Hum, I can't say I seen this behvaour.
But, just drop in two templated buttons and you off to the races so to speak. Because you NOT REALLY using the built in edit and features of those buttons, then little is to be gained by "half" using the built in buttons that way. So just template two buttons like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelectD" runat="server"
Text="Select" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDeleteRecord" runat="server"
Text="Delete" CommandName="Delete"
OnClientClick="return confirm('Are you sure you want to delete this item?');" />
</ItemTemplate>
</asp:TemplateField>
And as a result, you are free to attach events to each button to do whatever you want.
Note in the code editor, you will see this during editing of the markup and you ARE given a chance to create + add a event stub for buttons inside of that gridview etc.
Now if the button was outside of the gridview/listview/repeater etc., then you can normally just double click on the button and jump to the codebehind IDE. But when the button is inside of a repeating object, then you can't double click to create + build the event stub, but if you edit in markup as per above, then note how you see that dropdown appear - and you can choose create new event. Choose that, but you THEN have to flip over to code behind - and you will/should see the code stub.

"Failed to load view state" Error When dynamically loading user control

I am having a User control [ascx] which is a radgrid. It also has a Edit column template which allow user to Insert/ change/update the values.
I am loading this user control on click of a button [Say EDIT] in aspx page.
When I click on EDIT button of aspx page the user control loads perfectly, but when I click on the Add New Record of user control I get this error message.
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.
//code of user control -ascx
<telerik:RadGrid AllowAutomaticDeletes="True"
AllowAutomaticInserts="False" AllowAutomaticUpdates="False"
Height="410px" ID="rgrd1" runat="server" AutoGenerateColumns="False"
OnUpdateCommand="rgrd1_UpdateCommand"
OnInsertCommand="rgrd1_InsertCommand" OnNeedDataSource="rgrd1_NeedDataSource" GridLines="None">
<MasterTableView CommandItemDisplay="top" CommandItemStyle-Wrap="False" CommandItemStyle-HorizontalAlign="Left"
DataKeyNames="Type">
<Columns>
<telerik:GridEditCommandColumn UniqueName="EditColumn" HeaderStyle-HorizontalAlign="left"
HeaderText="Edit" ButtonType="ImageButton">
</telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn DataField="Type" HeaderStyle-HorizontalAlign="left"
HeaderText="Type" UniqueName="Type">
<ItemTemplate>
<asp:Label ID="TypeLabel" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<EditFormSettings EditFormType="Template">
<EditColumn FilterControlAltText="Filter EditCommandColumn1 column" UniqueName="EditCommandColumn1">
</EditColumn>
<FormTemplate>
<table>
<td>
<telerik:RadTextBox ID="txtType" Width="50" runat="server" Text='<%# Eval("Type") %>'>
</telerik:RadTextBox>
</td>
</tr>
</table>
</FormTemplate>
</EditFormSettings>
</MasterTableView>
<HeaderStyle HorizontalAlign="Center" />
</telerik:RadGrid>
.....................................
Code of my aspx page - in which i am loading the above usercontrol in Radwindow
On click of EDIT button - below code i have written-
RadWindow window = new RadWindow();
window.Height = Unit.Pixel(500);
window.Width = Unit.Pixel(500);
window.VisibleOnPageLoad = true;
UserControl uc = (UserControl)Page.LoadControl("../../Controls/TypeUserControl.ascx");
uc.EnableViewState = false;
window.ContentContainer.Controls.Add(uc);
pnl.Controls.Add(window);
When I click on Add New Record in usercontrol it throws the exception "Failed to load view state:"
I have aspx page on which this user control is loaded is being inherited by my BasePage.
Exception is coming in OnPreRender of base page
protected override void OnPreRender(EventArgs e)
{
try
{
base.OnPreRender(e);
}
}
User control - code behing
public partial class TypeUserControl : System.Web.UI.UserControl
{
protected void rgrd1Types_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
//dbase call
}
catch (Exception ex)
{
SetValidationMessage(ex.Message.ToString());
}
}
protected void rgrd1_InsertCommand(object source, GridCommandEventArgs e)
{
try
{
//dbase call
}
catch (Exception ex)
{
SetValidationMessage(ex.Message.ToString());
}
}
I don't know if this is the issue, but your HTML is not correct in your Form Template
<table>
<td>
<telerik:RadTextBox ID="txtType" Width="50" runat="server" Text='<%# Eval("Type") %>'>
</telerik:RadTextBox>
</td>
</tr>
</table>
you are missing the opening <tr> tag. this could have something to do with the issue.
you should double check all your code to make sure that it is correct.
--
I am also guessing that you should remove this line of code from the Edit button's OnClick() event
uc.EnableViewState = false;
You have to recreate the control on postback as you add it dynamically.
Recreate or Add the control in the Init_page Eventhandler, there you can check the type of event or control, that caused the postback, to know that you should recreate this control.
Can you post the code-behind file.
EDIT:
It's a long time ago, when I did this. But here is a working example.
I think there is a better way.
Check the keys collection, which button caused the postback, if it is a certain button in your ascx control then readd your control to the page or whereever you put it, but it must be the same place on postback, otherwise you will get an error, I think.
protected override void OnInit(EventArgs e) { base.OnInit(e);
if (this.Page.IsPostBack) {
var x = base.DeterminePostBackMode();
if (x.Keys.Get(3).Contains("btnInControl"))
{
Control ctrl = Page.LoadControl("WebUserControl1.ascx");
this.Page.Form.Controls.Add(ctrl);
}
}
}
It has been a year since you posted this issue but just in case someone still facing this: here is the main root of this type of error. I have been struggling big time with it.
The easiest way to fix your bug is to set to the control you add dynamically :
EnableViewState = false
If you need the Viewstate, the other options you have are to add the control you add dynamically onInit, or recreate it on every Postback.
Hope it helps.
See Funkylife's comment for more information.

Fire Gridview RowUpdating Event without an Update/Save Button

I have a gridview and I would like to Autosave the fields without using a save or an update button. How do I fire the RowUpdating Event without using a button? Or is there a better way of implementing this? Thanks for your help.
<div id="form_BCFLP" class="fm_Medium5" runat="server" visible="true">
<asp:GridView ID="GV_BCFLP" runat="server" AutoGenerateColumns="False" DataKeyNames="Id,Name"
GridLines="none" Visible="true" OnRowUpdating="GV_BCFLP_RowUpdating" EnableViewState="true" AutoPostback="true">
<Columns>
<asp:BoundField DataField="Name" ItemStyle-HorizontalAlign="left" ItemStyle-CssClass="lblSize_LargeBlack"></asp:BoundField>
<asp:TemplateField ItemStyle-HorizontalAlign="left">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
protected void GV_BCFLP_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//I call my webservice here to update data
}
Using the RowUpdating event requires you to do a post back which probably is not what you are looking for. For proper auto saving you dont want to (typically) disrupt the user while they are filling in the form.
Instead you may want to look at using aJAX and javascript script functions to extract the entered data from the grid view and send it to your server. This way the user does not have to wait for your auto-save to finish before continuing the form.
Now there are lots of tutorials out there on how to use aJax and other scripting tools. I would suggest going down this route.
Cheers,
Nico

ASP.net C# Gridview ButtonField onclick event

I've written an ASP code for a webshop type project. There is a method that adds the ProductID to a cookie and adds 1 to the quantity of the product.
Another method reads the cookie, transforms the cookie to a data table and puts it in a gridview. This gridview basically is the shoppingcart.aspx page.
What i now need is a way to add a buttonfield to that gridview where i can add a ++ button (like the add to shopping cart button on a product page), normal asp buttons take a onclick="methodname" but these in the gridview don't.
add1ToShoppingCart(string productId)
{[...]shoppingCartCookie[productId] = (amount + 1).ToString();}
That is the code I use for all the ++ buttons. It takes the button.id (buttonID=productID). So I need a way to have all the buttons be the same image, but the buttonID has to be databound to the productID so it can somehow execute that method (with some sort of onclick="").
I've looked and googled for the past couple hours but I cant seem to find anything. In the past I found a lot of answers on stackoverflow so I hoped somebody here could help.
Thanks in advance.
you can use Template field :
<asp:TemplateField ItemStyle-Width="33px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
ShowHeader="false" HeaderStyle-Height="40px">
<ItemTemplate>
<asp:ImageButton ID="btnAddToCard" runat="server" ImageUrl="~/Images/btnAddToCard.png" CausesValidation="false"
CommandName="AddToCard" CommandArgument='<%# Eval("ID") %>'
/>
</ItemTemplate>
<HeaderStyle Height="40px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="33px"></ItemStyle>
</asp:TemplateField>
and in your C# code behind you create the following event of your gridview and do what you want :
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCard")
{
//Write code to add to card
}
}
GV is the ID of my GridView !

gridview editing

In my web page i used a gridview. In this gridview it shows a group of users information.
I just added one button from smart tag menu. And my requirement is that when i am hitting the button corresponding to each users, it will redirect to another page and shows the corresponding user's information. What i do for getting this type of output?
U have to add the button and add an attribute CommandName:
<asp:Button ID="EditBtn" runat="server" CommandName="Edit" />
then in the event of itemcommand of the grid do the following
protected void GridView1_ItemCommand(object source, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
//Redirect to user page information
Response.Redirect(PageURL);
}
}
Ahmy's answer is the way to go if you want to use a button and have your page redirect to another page with the user's information. One thing that was left out however was that you can pass a command argument through the button (like the user's unique ID) which you could then put in the querystring of the page you are redirecting to, to identify which user it is. That would look like this:
<asp:TemplateField HeaderText="Edit User">
<ItemTemplate>
<asp:Button ID="EditBtn" Text="Edit User" CommandName="Edit"
CommandArgument='<%# Eval("UserID") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
Then in the code behind
protected void GridView1_ItemCommand(object source, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
//Redirect to user page information
Response.Redirect("UserProfilePage.aspx?userID=" + e.CommandArgument);
}
}
Another alternative to using a button, which I think is the best option is to use a HyperLinkField. When using a button, the page will have to post back to the server, then send a redirect to the user's browser. With a hyperlink, the user goes straight to the correct page. It saves a step and doesn't rely on javascript.
<asp:HyperLinkField DataTextField="UserName" DataNavigateUrlFields="UserID"
DataNavigateUrlFormatString="UserProfilePage.aspx?userID={0}"
HeaderText="Edit User" />
Instead of button, make one of the column hyperlinked. On clicking the item, redirect to your new page (using Javascript). By this you can avoid an additional column for the button and a postback.
You must use DataTextFormatString for this.
Sample
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="no" HeaderText="SNo" />
<asp:BoundField DataField="file" DataFormatString="<a href=javascript:ShowAssetDetail('{0}');>{0}</a>"
HeaderText="Asset Desc" HtmlEncodeFormatString="False" />
</Columns>
</asp:GridView>
In above sample the JS function ShowAssetDetail() must take a value to pass to the redirecting page. Needless to say, the JS function must be written in addition.

Categories

Resources