I'm trying to get the original object back from a listview, when I click on the button.
I thought it was in e.Item.DataItem but that always seems to be null.
<form runat="server">
<asp:ListView ID="ListList" runat="server">
<ItemTemplate>
<asp:TextBox ID="tbCompanyName" runat="server" Text='<%# Eval("CompanyName") %>'></asp:TextBox>
<asp:TextBox ID="tbEmailAdress" runat="server" Text='<%# Eval("EmailAddres") %>'></asp:TextBox>
<asp:DropDownList ID="ddlAccountManagers" AutoPostBack="True" runat="server" />
<asp:Button runat="server" Text="Create or Update Account" CommandArgument='<%# Container.DataItem.ToString() %>' />
<br />
</ItemTemplate>
</asp:ListView>
</form>
private void ListList_ItemCommand(object sender, ListViewCommandEventArgs e)
{
}
You need to keep the original datasource in session and get the real values while clicking a button.
Related
I have a fairly simple FormView control I'm using with ASP.Net/C#. My issue is when I use the code to redirect after the update/edit, the FormView won't actually perform the update, but, it will Redirect. I won't post all of the FormView code because it does update when I comment out the Redirect code. I think what I am asking is how to change the code to update while using the Redirect Code? Again, the update works fine when I don't do the Redirect! Is it possible the redirect is happening before the update can take place?
Code for Redirect
<script runat="server">
protected void FormView1_ItemUpdating(Object sender, FormViewUpdateEventArgs e)
{
{
Response.Redirect("redirect_main.aspx");
}
}
</script>
FormView1
<asp:FormView ID="FormView1" runat="server" onitemupdating="FormView1_ItemUpdating" DataKeyNames="req_submitted_key" DataSourceID="SqlDataSource2" DefaultMode="Edit" >
<EditItemTemplate>
req_submitted_key:
<asp:Label ID="req_submitted_keyLabel1" runat="server" Text='<%# Eval("req_submitted_key") %>' />
<br />
Role_job_title:
<asp:TextBox ID="Role_job_titleTextBox" runat="server" Text='<%# Bind("Role_job_title") %>' />
<br />
requestname:
<asp:TextBox ID="requestnameTextBox" runat="server" Text='<%# Bind("requestname") %>' />
<br />
submitted_by_name:
<asp:TextBox ID="submitted_by_nameTextBox" runat="server" Text='<%# Bind("submitted_by_name") %>' />
<br />
Submitted_by_email:
<asp:TextBox ID="Submitted_by_emailTextBox" runat="server" Text='<%# Bind("Submitted_by_email") %>' />
<br />
submitted_date:
<asp:TextBox ID="submitted_dateTextBox" runat="server" Text='<%# Bind("submitted_date") %>' />
<br />
submitted_by_comment:
<asp:TextBox ID="submitted_by_commentTextBox" runat="server" Text='<%# Bind("submitted_by_comment") %>' />
<br />
approved_denied:
<asp:TextBox ID="approved_deniedTextBox" runat="server" Text='<%# Bind("approved_denied") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
Yes...it redirecting before the update. Take your redirect out of ItemUpdating and put it in ItemUpdated.
From: DetailsView.ItemUpdatint Event
DetailsView.ItemUpdating Event
Occurs when an Update button within a DetailsView control is clicked,
but before the update operation.
DetailsView.ItemUpdated Event
Occurs when an Update button within a DetailsView control is clicked,
but after the update operation.
DetailsView.ItemUpdated Event
Your code should look like:
protected void FormView1_ItemUpdated(Object sender, FormViewUpdateEventArgs e)
{
Response.Redirect("redirect_main.aspx");
}
The Asp.net website I am creating uses a Repeater to display a list of Strings concerning duplicates or missing entries from two databases. There is another list of strings created in parallel of SQL statements with one SQL statement corresponding to the same numbered string in the Repeater list. The number of strings in the lists depends on the databases chosen and can range from zero to 100+.
Question: Since the number of Repeater rows are unknown, I am trying to find some method to generate an unknown number of checkboxes/buttons (one for each row). When clicked, the checkbox/button will find the appropriate SQL statement in the other list for the row in a separate method. Does anyone have an idea as to how a variable number of checkboxes could be created?
This can be done with adding a CommandArgument to a button and assigning a Command to it, not a Click.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("myColumn") %>'></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("ID") %>' OnCommand="Button1_Command" Text="Button" />
<hr />
</ItemTemplate>
</asp:Repeater>
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
And then in code behind handle the OnCommand
protected void Button1_Command(object sender, CommandEventArgs e)
{
Label2.Text = e.CommandArgument.ToString();
}
If you want to read a CheckBox, you'll need slighty more code in code behind.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("field01") %>'></asp:Label>
<br />
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Convert.ToBoolean(Eval("itemid")) %>' />
<br />
<asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("itemid") %>' OnCommand="Button1_Command" Text="Button" />
<hr />
</ItemTemplate>
</asp:Repeater>
protected void Button1_Command(object sender, CommandEventArgs e)
{
Button btn = sender as Button;
RepeaterItem item = (RepeaterItem)btn.NamingContainer;
CheckBox cb = item.FindControl("CheckBox1") as CheckBox;
Label2.Text = "Item with ID " + e.CommandArgument + " has checkbox " + cb.Checked;
}
Here's the thing. I have a ASP.NET Web Application in C#. In the Default.aspx I have an UpdatePanel containing all the elements. There, I have three validators associated with a TextBox, 4 RadioButton (two belong two one group and the other two to another group) and for each group I have a validator in order to verify if one element was checked for each group. For all RadioButton the AutoPostBack is set to "True" because when the "No" option is selected for both groups then I will enable a multi-line TextBox so the user can input some text. There's also a ValidationSummary at the end that displays error messages in a pop-up box and in the page as well. The main issue is the following: if I first select the two options from the RadioButtons and then click in the submit button, without input any text in the TextBox with the 3 validators, I will get 3 pop-up error messages. And more interesting, if I select after the 3 pop-up error messages another option from any of the RadioButton groups, I will get 4 pop-up error messages. I have a guess that it has to do with the AutoPostBack attribute of the RadioButton because it happens when I click them, but I don't know why or how to fix it.
Here's the code for Default.aspx:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="M-DCPS 7-digit Student ID#:"></asp:Label>
<asp:TextBox ID="studentIDtbox" runat="server" MaxLength="7" Width="6%" CausesValidation="false"></asp:TextBox>
<asp:RequiredFieldValidator Font-Size="Large" ID="RequiredFieldValidatorAccount" runat="server" ControlToValidate="studentIDtbox"
ErrorMessage="ID# required" ForeColor="Red">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator Font-Size="Large" ID="RegularExpressionValidator2" runat="server" ControlToValidate="studentIDtbox" ErrorMessage=" ID requires 7 digits" ValidationExpression="^[\s\S]{7,}$" ForeColor="Red">*</asp:RegularExpressionValidator>
<asp:RegularExpressionValidator Font-Size="Large" ID="RegularExpressionValidator1" runat="server" ControlToValidate="studentIDtbox"
ErrorMessage=" ID only accepts numbers" ValidationExpression="^\d+$" ForeColor="Red">*</asp:RegularExpressionValidator>
<asp:Label ID="Label2" runat="server" Text="Paper Form:"></asp:Label>
<asp:DropDownList ID="paperForm" runat="server"></asp:DropDownList>
<asp:Label ID="Label3" runat="server" Text="Paper Accommodation:"></asp:Label>
<asp:DropDownList ID="paperType" runat="server"></asp:DropDownList>
<asp:CustomValidator Font-Size="Large" runat="server" ID="cvIEP" OnServerValidate="cvIEP_ServerValidate"
Enabled="true" Display="Dynamic" SetFocusOnError="true" ErrorMessage="You must select at least one item for documentation on IEP/Section 504." ForeColor="Red">*</asp:CustomValidator>
<asp:Label ID="Label4" runat="server" Text="Paper is documented?"></asp:Label>
<asp:RadioButton ID="iepYesRb" runat="server" GroupName="IEPRequirement" Text="Yes" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:RadioButton ID="iepNoRb" runat="server" GroupName="IEPRequirement" Text="No" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:CustomValidator Font-Size="Large" runat="server" ID="cvRuse" OnServerValidate="cvRuse_ServerValidate"
Enabled="true" SetFocusOnError="true" ErrorMessage="You must select at least one item for regular use." ForeColor="Red">*</asp:CustomValidator>
<asp:Label ID="Label5" runat="server" Text="Is it used regularly?"></asp:Label>
<asp:RadioButton ID="ruseYesRb" runat="server" GroupName="RegularUse" Text="Yes" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:RadioButton ID="ruseNoRb" runat="server" GroupName="RegularUse" Text="No" OnCheckedChanged="rButton_CheckedChanged" AutoPostBack="True" CausesValidation="false"/>
<asp:Label ID="Label6" runat="server" Text="Provide other evidence if two 'No' where selected."></asp:Label>
<asp:TextBox ID="evidenceTbox" Style="height: 130px" runat="server" TextMode="MultiLine" Width="100%" Enabled="false"></asp:TextBox>
<asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submit_OnClick" />
<asp:ValidationSummary ID="valTest" runat="server" ShowMessageBox="true" BackColor="LightYellow" ForeColor="Red" Width="100%" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="submitButton" />
<asp:AsyncPostBackTrigger ControlID="iepYesRb" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="iepNoRb" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="ruseYesRb" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="ruseNoRb" EventName="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>
And here's the code for Default.aspx.cs:
protected void rButton_CheckedChanged(object sender, EventArgs e)
{
evidenceTbox.Enabled = iepNoRb.Checked && ruseNoRb.Checked;
}
protected void cvIEP_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = iepNoRb.Checked || iepYesRb.Checked;
}
protected void cvRuse_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = ruseNoRb.Checked || ruseYesRb.Checked;
}
protected void submit_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alerts", "javascript:alert('Record inserted properly')", true);
}
}
Any help will be appreciated and critics will be very welcome. Thanks.
<asp:DataList ID="DataListDziennik" runat="server"
DataSourceID="SqlDataSourcePrzedmioty">
<ItemTemplate>
<asp:Label ID="LabelPrzedmiot" runat="server" Text='<%# Eval("przedmiot") %>' />
...
<asp:DataList ID="DataListOceny" runat="server"
DataSourceID="SqlDataSourceOceny"
RepeatDirection="Horizontal"
OnItemCommand="DataListOceny_ItemCommandOceny"
OnEditCommand="DataListOceny_EditCommandOceny">
<EditItemTemplate>
<asp:TextBox ID="TextBoxOcena" runat="server" Text='<%# Bind("lista") %>' />
<td><asp:Button ID="ButtonZapisz" CommandName="Update" runat="server" Text="Zapisz" /></td>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox Width="20" ID="TextBoxOcena" ReadOnly="true" Text='<%# Eval("lista") %>' runat="server"></asp:TextBox>
<td><asp:Button ID="ButtonEdytuj" CommandName="Edit" runat="server" Text="Edytuj" /></td>
</ItemTemplate>
</asp:DataList>
</td>
</ItemTemplate>
When I write this in code behind:
protected void DataListOceny_EditCommand(object source, DataListCommandEventArgs e)
{
DataListOceny.EditItemIndex = e.Item.ItemIndex;
DataListOceny.DataBind();
}
Visual Studio tells me that DataListOceny does not exist in current content. I just want to be able edit items on DataListOceny after clicking the "edit" button, please give me full code in code behind part...
for edit DataListOceny .
What you asking is same like the below thread.. You need to find the DataListOceny Control on each row of DataListDziennik to bind it
Using FindControl() to find control
https://msdn.microsoft.com/en-us/library/486wc64h%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
And Here is some good example on the same
http://www.c-sharpcorner.com/UploadFile/rohatash/nested-datalist-in-Asp-Net/
http://surecode.net/DevCentre/NestedDataList/NestedDataList.aspx
First off, I am not dynamically creating any controls. This is the order I take to produce the error:
I have a listview on the page, when I click the edit link under the listview, I display a panel which is hidden by default. The panel has a few buttons on it along with some listboxes. When I click an item in the listbox or click one of the buttons, I get the following error:
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.
Again, I am not creating anything dynamically, I am just hiding the panel with the controls by default and then displaying them, so I am not sure why I am getting this error.
Here is some code:
PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["Albums"] = null;
Albums = AlbumCollection.GetAlbums(Common.GetUserName(),
ddlAlbumType.SelectedIndex);
lvwAlbums.DataSource = Albums;
lvwAlbums.DataBind();
}
}
When I click the edit link, this is the code that runs:
protected void lvwAlbums_RowEditing(object sender, ListViewEditEventArgs e)
{
this.AlbumId = int.Parse(
this.lvwAlbums.DataKeys[e.NewEditIndex].Values["AlbumId"].ToString());
this.AlbumName=
this.lvwAlbums.DataKeys[e.NewEditIndex].Values["AlbumName"].ToString();
Album album = new Album(this.AlbumId);
ViewState["AlbumId"] = this.AlbumId;
ViewState["AlbumName"] = this.AlbumName;
pnlAlbum.Visible = true; // This panel holds the controls
btnEditAlbum.Visible = true;
btnCancel.Visible = true;
EditAlbum(this.AlbumId);
this.lvwAlbums.EditIndex = e.NewEditIndex;
AlbumCollection.GetAlbums(Common.GetUserName(),ddlAlbumType.SelectedIndex);
}
If I click the cancel button, I get the error, but it also happens if click another button on the panel such as Add/Remove... Here is the code for the Cancel button:
pnlAlbum.Visible = false;
this.lvwAlbums.EditIndex = -1;
AlbumCollection.GetAlbums(Common.GetUserName(), ddlAlbumType.SelectedIndex);
Here is the aspx/html for the ListView:
<asp:ListView ID="lvwAlbums"
runat="server"
GroupItemCount="5"
DataKeyNames="AlbumId,AlbumName"
OnItemEditing="lvwAlbums_RowEditing"
OnItemCommand="lvwAlbums_ItemCommand"
OnItemDeleting="lvwAlbums_RowDeleting"
OnSelectedIndexChanging="lvwAlbums_SelectedIndexChanging"
OnPagePropertiesChanging="lvwAlbums_PagePropertiesChanging">
<EditItemTemplate>
<td>
<div>
<asp:TextBox ID="txtAlbumName" runat="server"
Text='<%# Eval("AlbumName").ToString().Trim() %>' />
<asp:LinkButton ID="lnkView" runat="server" Text="View" CommandName="View"
CommandArgument='<%# Eval("AlbumId") %>'>
</asp:LinkButton>
|
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit"
CommandArgument='<%# Eval("AlbumId") %>'>
</asp:LinkButton>
|
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName="Delete"
CommandArgument='<%# Eval("AlbumId") %>'>
</asp:LinkButton>
<br />
<span>Songs:
<%# Eval("total") %></span>
</div>
</td>
</EditItemTemplate>
<LayoutTemplate>
<asp:DataPager runat="server" ID="ItemDataPager" PageSize="20"
PagedControlID="lvwAlbums">
<Fields>
<asp:NumericPagerField ButtonType="Link" NumericButtonCssClass="pager" />
</Fields>
</asp:DataPager>
<table>
<tr>
<td>
<table>
<asp:PlaceHolder runat="server" ID="groupPlaceHolder"></asp:PlaceHolder>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder"></asp:PlaceHolder>
</tr>
</GroupTemplate>
<ItemTemplate>
<td>
<asp:Literal ID="litAlbumName" runat="server"
Text='<%# Eval("AlbumName").ToString().Trim() %>' />
<br />
<asp:LinkButton ID="lnkView" runat="server" Text="View" CommandName="View"
CommandArgument='<%# Eval("AlbumId") %>'>
</asp:LinkButton>
|
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit"
CommandArgument='<%# Eval("AlbumId") %>'>
</asp:LinkButton>
|
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName="Delete"
CommandArgument='<%# Eval("AlbumId") %>'>
</asp:LinkButton>
<br />
<span>Songs:
<%# Eval("total") %></span>
</td>
</ItemTemplate>
</asp:ListView>
Here is the markup for the Panel:
<asp:Panel ID="pnlAlbum" runat="server" Visible="false">
<asp:ListBox ID="lstAvailableSongs" runat="server" SelectionMode="Multiple">
</asp:ListBox>
<asp:Button ID="btnAddAll" runat="server" Text="Add All" OnClick="btnAddAll_Click" />
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<asp:Button ID="btnRemove" runat="server" Text="Remove" OnClick="btnRemove_Click" />
<asp:Button ID="btnRemoveAll" runat="server"
Text="Remove All"OnClick="btnRemoveAll_Click" />
<asp:ListBox ID="lstSelectedSongs" runat="server" SelectionMode="Multiple">
</asp:ListBox>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
<asp:Button ID="btnEditAlbum" runat="server"Text="Save"
ValidationGroup="CreateAlbum" OnClick="btnEditAlbum_Click" />
<asp:Button ID="btnSaveAs" runat="server" Text="Save As" ValidationGroup="CreateAlbum"
OnClick="btnSaveAs_Click" />
</asp:Panel>
Here is some extra info:
I put an update panel around one of the listboxes in the panel and when I clicked the edit link under a listview item, I received the following error:
Microsoft JScript runtime error: Sys.InvalidOperationException: Could not find UpdatePanel with ID 'ctl00_ctl00_InnerContent_MainContent_UpdatePanel4'. If it is being updated dynamically then it must be inside another UpdatePanel.
Putting an UpdatePanel around the whole asp.net panel resolved the issue above, but I still get the Failed to load viewstate error when clicking on Cancel or Add, etc...
First off, you probably need to rebind the ListView after setting the EditIndex. (honestly, I haven't used ListView at all, but this is how the other repeater controls work) What does "EditAlbum()" do?
Your code is a little odd... why do you have the same controls in your EditItemTemplate as in the ItemTemplate? Ie, the Edit button should only be in the ItemTemplate... Then EditItemTemplate should have a Save or Cancel button.
Bottom line... your control tree is different on LoadViewState than it is when SaveViewState was called. One thing you can do is override these methods and then put a breakpoint there to manually look at the Controls collection in the debugger. You will probably see that the controls inside the ListView are different. But try my first suggestion before you do this.
Question for you:
in your Page_Load you have
Albums = AlbumCollection.GetAlbums(Common.GetUserName(), ddlAlbumType.SelectedIndex);
but in lvwAlbums_RowEditing(..) and in btnCancel_Click(...) you have
AlbumCollection.GetAlbums(Common.GetUserName(), ddlAlbumType.SelectedIndex);
shouldn't these be (Albums = ...)
Albums = AlbumCollection.GetAlbums(Common.GetUserName(), ddlAlbumType.SelectedIndex);