ASP.NET GridView inside UpdatePanel won't get out of Edit Mode - asp.net

I have a pretty standard GridView with an SqlDataSource complete with SelectCommand/UpdateCommand/DeleteCommand.
I am utilising the Gridview's built-in commands for TemplateField'ed 's.
CommandName="Update"
CommandName="Edit"
CommandName="Cancel"
CommandName="Delete"
Everything works OK until I put the GridView inside an UpdatePanel.
1. When I click on 'edit' it goes into edit mode but won't get out of edit mode when you click Cancel or Update.
2. When I click on 'delete' performs as it should, however, I won't be able to get into edit mode anymore even if I click 'edit'
What's the matter here?
Example code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="BoxFloat">
<h4>Aliases</h4>
<hr />
<asp:SqlDataSource ID="sqlPersonAlias" runat="server"
ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
ProviderName="<%$ ConnectionStrings:myConnectionString.ProviderName %>"
DeleteCommand="DELETE FROM PersonAlias WHERE PersonAliasId=?PersonAliasId"
UpdateCommand="UPDATE PersonAlias SET AliasName=?AliasName WHERE PersonAliasId=?PersonAliasId"
SelectCommand="SELECT * FROM PersonAlias E INNER JOIN Person P ON P.PersonId=E.PersonId WHERE Username=?Username">
<DeleteParameters>
<asp:Parameter Name="PersonAliasId" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="PersonAliasId" />
<asp:Parameter Name="AliasName" />
</UpdateParameters>
<SelectParameters>
<asp:QueryStringParameter Name="Username" QueryStringField="Username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="gridviewPersonAlias" runat="server"
AutoGenerateColumns="False"
DataKeyNames="PersonAliasId"
DataSourceID="sqlPersonAlias">
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:ImageButton ID="imagebuttonCancel" ToolTip="Cancel" CommandName="Cancel" ImageUrl="~/images/cancel16.png" runat="server" />
<asp:ImageButton ID="imagebuttonUpdate" ToolTip="Apply" OnClientClick="return confirm('Are you sure?');" CommandName="Update" ImageUrl="~/images/apply16.png" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imagebuttonDelete" ToolTip="Delete" OnClientClick="return confirm('Are you sure?');" CommandName="Delete" ImageUrl="~/images/delete16.png" runat="server" />
<asp:ImageButton ID="imagebuttonEdit" ToolTip="Edit" CommandName="Edit" ImageUrl="~/images/edit16.png" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AliasName" HeaderText="Alias" SortExpression="AliasName" />
</Columns>
</asp:GridView>
<hr />
<asp:TextBox ID="textboxPersonAlias" runat="server" />
<asp:Button ID="buttonPersonAliasAdd" runat="server" Text="Add" onclick="buttonPersonAliasAdd_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
When "Update" is clicked, the database gets updated. It seems that the problem is just with the client-side.
Note: I'm using "?" instead of "#" for the parameters because that SqlDataSource is using MySq instead of MSSQL (I love VS2010).

I think what you need is full Postback or refresh the update Panel since it is most likely the gridview doesnt rebind
First try to put the sqldatasource outside the update panel. See if that works

I had the same problem in my project, and solved it.
here is my solution:
protected void gvPayments_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//here is the edit code
//......
//at the end add these lines:
gvPayments.EditIndex = -1;
gvPayments.DataBind();
e.Cancel = true;
}

Related

Dropdown list change based on other dropdown list in details view ASP.NET

I have two dropdown lists in a detailsview one called College and the other is Department. If the user select a college, the department dropdown list should generate all the departments for the selected college.
Here is the detailsview and the dropdown lists:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="600px" AutoGenerateRows="False" CssClass="table table-bordered mtop" DataKeyNames="ID" DataSourceID="SqlDataSource1" OnDataBound="DetailsView1_DataBound">
<FieldHeaderStyle CssClass="DetailsViewHeader" Width="200px" />
<Fields>
<asp:TemplateField HeaderText="College" SortExpression="Colleges">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource3" DataTextField="ArName" DataValueField="Code"></asp:DropDownList>
<asp:HiddenField ID="HiddenColl" runat="server" value='<%# Eval("Colleges") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label15" runat="server" Text='<%# Bind("Colleges") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department" SortExpression="ArName">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="ArName" DataValueField="Code"></asp:DropDownList>
<asp:HiddenField ID="HiddenDep" runat="server" value='<%# Eval("ArName") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("ArName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:Button ID="Button2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
<asp:Button ID="btnDelete" runat="server" CausesValidation="False" Text="Delete" OnClientClick="return confirm('Do you want to delete ?');" OnClick="btnDelete_Click" />
</ItemTemplate>
<ControlStyle CssClass="btn-login" />
<ItemStyle CssClass="text-center" />
</asp:TemplateField>
</Fields>
</asp:DetailsView>
Here is the SqlDataSources:
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:UEDConnectionStringMarwaMarwa %>" SelectCommand="SELECT [ArName], [Code] FROM [College]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:UEDConnectionStringMarwaMarwa %>" SelectCommand="SELECT [Code], [ArName] FROM [Department] WHERE ([CollegeCode] = #CollegeCode)">
<SelectParameters>
<asp:ControlParameter ControlID="DetailsView1$DropDownList2" Name="CollegeCode" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
This is the error message:
Could not find control 'DetailsView1$DropDownList2' in
ControlParameter 'CollegeCode'
I did this DetailsView1$DropDownList2 so it can access the dropdown list that is inside the detailsview
What is the problem ?
I am unfamiliar with the DetailsView and not experienced with the SqlDataSource, but I will try to help.
In my experience, I have learned that you shouldn't try to assume a control's ClientID. So, first I would recommend getting the ClientID from the server control.
Using an inline expression, I would try something like this:
<asp:ControlParameter ControlID='<%= DetailsView1.Rows(0).FindControl("DropDownList2").ClientID %>' Name="CollegeCode" PropertyName="SelectedValue" Type="Int32" />
For more about asp.net inline expressions see Introduction to ASP.NET inline expressions in the .NET Framework.
Because I am unfamiliar with the DetailsView control, I don't know if there will be a row at index 0 in the DetailsView when it executes this inline expression (which would throw an exception).
If that code doesn't work, I would suggest dynamically setting the ControlID on the back end that executes after the DetailsView1 rows are bound (such as inside the DetailsView1's DataBound event method).
VB:
If DetailsView1.Rows.Count > 0 Then
Dim objDropDownList2 as Control = DetailsView1.Rows(0).FindControl("DropDownList2")
If objDropDownList2 IsNot Nothing Then
SqlDataSource1.SelectParameters("CollegeCode").ControlID = objDropDownList2.ClientID
End If
End If
C#:
if (DetailsView1.Rows.Count > 0) {
Control objDropDownList2 = DetailsView1.Rows(0).FindControl("DropDownList2");
if (objDropDownList2 != null) {
SqlDataSource1.SelectParameters("CollegeCode").ControlID = objDropDownList2.ClientID;
}
}
I hope this helps!

DeleteCommand not working in asp.net 2.0

I have the following SqlDataSource:
<asp:SqlDataSource ID="LDetails" runat="server" ConnectionString="<%$ ConnectionStrings:NormCon %>"
SelectCommand ="SELECT l.Link_ID,l.Link_Name,l.Link_Path,l.Link_Desc
FROM HyperLinks l
WHERE l.link_id = #Link_ID;"
UpdateCommand ="UPDATE Hyperlinks SET Link_Name = #Link_Name, Link_Path = #Link_Path, Link_Desc = #Link_Desc WHERE Link_ID = #Link_ID;"
DeleteCommand ="DELETE FROM Hyperlinks_Groups WHERE Join_Link = #Link_ID; DELETE FROM Hyperlinks WHERE Link_ID = #Link_ID;"
<SelectParameters>
<asp:ControlParameter Name="Link_ID" ControlID="linkList" PropertyName="SelectedDataKey.Value" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Link_Name" />
<asp:Parameter Name="Link_Path" />
<asp:Parameter Name="Link_Desc" />
<asp:ControlParameter Name="Link_ID" ControlID="linkList" PropertyName="SelectedDataKey.Value" />
</UpdateParameters>
<DeleteParameters>
<asp:ControlParameter Name="Link_ID" ControlID="linkList" PropertyName="SelectedDataKey.Value" />
</DeleteParameters>
</asp:SqlDataSource>
this is the detailsview I have:
<asp:DetailsView ID="LinkDetails" runat="server" DataSourceID="LDetails"
DataKeyNames="Link_ID" AutoGenerateRows="False" OnItemDeleted="deleteLinkReload" >
<Fields>
<asp:BoundField DataField="Link_ID" />
<asp:TemplateField HeaderText="Link Name">
<ItemTemplate>
<asp:Label ID="lblLinkName" runat="server" Text='<%# Bind("Link_Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLinkName" runat="server" Text='<%# Bind("Link_Name") %>' MaxLength="50" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<asp:HyperLink ID="lnkLinkPath" runat="server" Text='<%# Bind("Link_Path") %>' NavigateUrl='<%# Bind("Link_Path") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLinkActual" runat="server" Text='<%# Bind("Link_Path") %>' MaxLength="250" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:Label ID="lblLinkComment" runat="server" Text='<%# Bind("Link_Desc") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLinkComment" runat="server" Text='<%# Bind("Link_Desc") %>' MaxLength="250" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="linkDetailsEdit" runat="server" CommandName="edit" Text="Edit" />
<asp:LinkButton ID="linkDetailsDelete" runat="server" OnClientClick="return confirm('OK to delete link?');" CommandName="Delete" Text="Delete Link" /> <%--OnClick="DeleteLink" --%>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="linkDetailsAccept" runat="server" CommandName="update" Text="Accept" />
<asp:LinkButton ID="linkDetailsCancel" runat="server" CommandName="Cancel" CausesValidation="false" Text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
When I click a delete button in the detailsview which is linked to this, the page refreshes but the item is not deleted. I think the DeleteCommand is returning 0 rows or erroring without me being able to catch the error. I've tried seeing if its a case of the DeleteCommand even firing by switching the SQL to this:
DeleteCommand ="INSERT INTO mis_test (string) VALUES ('Hi');"
and it still didn't do anything. Any ideas?
Try using SQL Server Profiler to see what is run on the database, and what error it gives.
I would bet that your connection string includes things like User Instance=true and AttachDbFileName=..., and that after you run the delete command, you are connecting via SSMS or Visual Studio (not your app) and checking the table.
If this is the case, then you need to stop using this User Instance feature (which has been deprecated). What this does is create a copy of your database for each instance of any application that connects.
What you need to do is properly attach your database to a real instance of SQL Server, and connect to that copy of the database from all applications.

How to bind dropdownlist in EditItemTemplate in FormView control?

Using Visual Web Developer Express 2010 with ASP.NET 4.0.
I have a FormView and I want to set a default value from the database. I can't get it to bind to the value in the database. My FormView looks like this:
<asp:FormView
ID="frmOrderDetails"
DataSourceID="sdsFormOrderDetails"
runat="server"
DataKeyNames="orderId">
<EditItemTemplate>
<h3>Edit Order Details</h3>
<asp:Label ID="lblStrategy" Text="Strategy:" AssociatedControlID="ddlStrategies" runat="server" />
<asp:DropDownList SelectedValue='<%# Bind("strategyId") %>'
ID="ddlStrategies"
runat="server"
DataTextField="strategy"
DataValueField="strategyId"
DataSourceID="sdsStrategies"
/>
<asp:LinkButton
id="lnkUpdate"
Text="Update Order"
CommandName="Update"
Runat="server" />
|
<asp:LinkButton
id="lnkCancel"
Text="Cancel"
CommandName="Cancel"
Runat="server" />
</EditItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="sdsFormOrderDetails" runat="server"
ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>"
ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>"
SelectCommand="usp_GetOrderDetails" SelectCommandType="StoredProcedure"
UpdateCommand="usp_UpdateOrder" UpdateCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Name="orderId" ControlID="grdOrders" PropertyName="SelectedDataKey.Value" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter Name="orderId" ControlID="grdOrders" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="sdsStrategies" runat="server"
ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>"
ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>"
SelectCommand="usp_GetStrategiesDropDown">
</asp:SqlDataSource>
The EditItemTemplate does not even load when I click the edit button on my FormView control, but I don't get an error message either.
You need to do the following to bind a DropDownList to the EditItemTemplate:
Add the DropDownList and its DataSource to the EditItemTemplate.
Set the DropDownList parameters:
DataSourceID="SqlDataSourceDropDownlist" SelectedValue=<%# Bind("ValueToBind") %>
DataTextField="ValueToDisplay" DataValueField="ValueToBind"
Set the ListView / FormView DataSource <UdateParameters>: <asp:Parameter Name="RankID" Type="Int32" />
you need to use formview Databound event like
protected void frmOrderDetails_DataBound(object sender, EventArgs e)
{
if (frmOrderDetails.CurrentMode == FormViewMode.Edit)
{
DropDownList ddlStrategies = (DropDownList)frmOrderDetails.FindControl("ddlStrategies");
ddlStrategies.SelectedValue = Your DB Value Goes here;
}
}

Filter gridview

I have a gridview which I am binding through code behind, I want to filter the gridview based on the value given by the user in textbox.
It would be great if I'll be able to filter the gridview without any postback.
PLease help!
Thanks in advance
you could run a filter expression
<asp:sqldatasource id="articles" runat="server"
connectionstring="<%$ ConnectionStrings:aspa %>"
selectcommand="SELECT title, url, added, updated FROM aspx_articles ORDER BY title"
filterexpression="title LIKE '%{0}%' or url LIKE '%{0}%'">
<filterparameters>
<asp:controlparameter controlid="searchBox" propertyname="Text" />
</filterparameters>
</asp:sqldatasource>
or this way
Do you have a TextBox outside the GridView, and when you enter data into it and press a button, the GirdView should be filter on that data?
If so, make sure your select command can taka a parameter with the value you want to filter on. Add a ControlParameter to the SelectParameters colelction of the DataSource control (if you use a DataSource control).
Here is an example that uses the Northwind database, maybe this will help you:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ShowFooter="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitsInStock], [UnitPrice] FROM [Alphabetical list of products] WHERE ([ProductName] LIKE '%' + #ProductName + '%')">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" DefaultValue="%" Name="ProductName" PropertyName="Text"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
codes found here http://forums.asp.net/p/1034014/2904713.aspx
If you're using paging, I would recommend using something else (like the Microsoft Ajax Library's dataView). Because gridview paging and client-side filtering wouldn't mesh too well. But if you're not doing paging, you could do something similar to this or this.
The grid view is made for manipulation during post back. If you were to do this entirely on the client side, you'd use a JavaScript suite that would work on any table, not confined to the grid view. If it were me, I would simply use AJAX by wrapping the grid view and text box in an Update Panel. To the end user, the behavior is the same.
EDIT to include Sample code:
<asp:ScriptManager ID="ScriptManager1" AllowCustomErrorsRedirect="false" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" ID="txtFilterString" ></asp:TextBox>
<asp:Button runat="server" ID="btnFilter" Text="FilterResults" onclick="btnFilter_Click" />
<asp:GridView runat="server" ID="grdResults"
DataKeyNames="Id"
AllowSorting="true" AllowPaging="true" PageSize="20"
PagerSettings-Mode="NumericFirstLast">
<Columns>
.....
</Columns>
</asp:GridView>
</asp:UpdatePanel>

AjaxControlToolkit DropDownExtender inside a table always displays associated panel

I have a textarea that has the ajaxcontroltoolkit dropdownextender associated with it, and a panel that contains a gridview with the options for the user to select from.
Here is the code for these items:
<asp:UpdatePanel ID="updPnlView" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtSiteName" runat="server" TextMode="MultiLine" Rows="4" Columns="33" ReadOnly="true" /></td>
<ajaxToolkit:DropDownExtender runat="server" ID="popupdropdown"
DropDownControlID="pnlGrid" TargetControlID="txtSiteName" />
<asp:Panel runat="server" ID="pnlGrid" Style="display: none; visibility: hidden" Height="300" ScrollBars="Vertical">
<asp:GridView ID="gvSite" runat="server" AutoGenerateColumns="False" Width="100%"
DataKeyNames="ID,FullAddress" DataSourceID="odsSite" OnRowDataBound="gvSite_RowDataBound"
ShowFooter="false" ShowHeader="false" OnSelectedIndexChanged="gvSite_SelectedIndexChanged" >
<Columns>
<asp:CommandField ButtonType="Link" SelectText="Select" ShowSelectButton="true" ItemStyle-CssClass="HiddenColumn" />
<asp:TemplateField >
<ItemTemplate>
<asp:Label ID="FullAddress" runat="server" Text='<%# Eval("FullAddress").ToString().Replace("\n", "<br/>") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CheckBoxField DataField="DisabledFLG" ItemStyle-CssClass="HiddenColumn" />
</Columns>
</asp:GridView>
</asp:Panel>
<asp:ObjectDataSource ID="odsSite" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetList"
TypeName="SOM.DCO.MOGWAI.Bll.SiteManager"
onselecting="odsSite_Selecting" SortParameterName="SortExpression"
onselected="odsSite_Selected" >
<SelectParameters>
<asp:Parameter Name="myCriteria" Type="Object" />
<asp:Parameter Name="myIDs" Type="Object" />
<asp:Parameter Name="sortExpression" Type="String" />
<asp:Parameter Name="bypassCache" Type="Boolean" />
</SelectParameters>
</asp:ObjectDataSource>
</ContentTemplate>
</asp:UpdatePanel>
When I place this item inside a table (i.e. <table><tr><td>THE CODE ABOVE</td></tr></table>) the panel always shows completely open never hidden. It also completely fills out the available space within the TD and pushes all other text on the page down the screen.
If I take the associated controls out of the table, it works as expected. I have duplicated this issue in both Firefox and IE8.
What gives?
well, with further testing, I was able to prove that this only happens if the control referenced by the dropdownextender is a gridview.
I changed it to a listview control instead and it works as it should.
I assume this is a bug, but I can't find any record of it anywhere.
I also tested to see if it had the same behavior when the gridview was inside a panel that was not referenced by the dropdownextender, but it did not occur. So it's definitely related to the dropdownextender.

Resources