I have a GridView object fed trough a SqlDataSource. In the same form I have also a number of TextBoxes used to build a filtering expression for the datasource. The filtering is started by pressing a Button.
<asp:GridView
DataSourceID="sdsTable1"
OnSorting="gvTable1_Sorting"
OnPageIndexChanging="gvTable1_PageIndexChanging"
runat="server"
CssClass="list_table"
ID="_gvTable1"
CellPadding="0" CellSpacing="0"
AutoGenerateColumns="false"
EmptyDataText="No data."
ShowHeader="true" ShowFooter="true"
AllowSorting="true"
AllowPaging="true"
PageSize="10"
OnRowDataBound="gvTable1_RowDataBound" >
<HeaderStyle CssClass="header" />
<FooterStyle CssClass="footer" />
<PagerSettings
Visible="true"
Mode="NumericFirstLast"
PageButtonCount="3"
Position="Bottom"
NextPageText="Next page"
PreviousPageText="Prev page"
FirstPageText="First page"
LastPageText="Last page" />
<RowStyle CssClass="odd" />
<AlternatingRowStyle CssClass="even" />
<PagerStyle HorizontalAlign="Center" />
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate> </HeaderTemplate>
<ItemTemplate>
<%#Eval("id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="date">
<ItemTemplate>
<%#Eval("date","{0:dd/MM/yyyy HH:mm:ss}")%>
</ItemTemplate>
<FooterTemplate>
TOTALE:
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("price","{0:F2} €") %>'>></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsTable1" runat="server"
ConnectionString="<%$ ConnectionStrings:_db %>"
ProviderName="<%$ ConnectionStrings:_db.ProviderName %>"
DataSourceMode="DataSet"
SelectCommand=" SELECT id, id_user, price, description FROM view1 WHERE id_user = #id_user;">
<SelectParameters>
<asp:SessionParameter Type="Int32" Name="id_user" SessionField="USER_ID" />
</SelectParameters>
</asp:SqlDataSource>
In codebehind (in the event hanlder associated with the Button mentioned above) I build up the filter expression chaining TextBoxes values, with this code:
if (!string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()))
{
_sFilter += "(description LIKE '%" + _txtFilter0.Text.Trim() + "%')";
}
if (!string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()))
{
if (!string.IsNullOrWhiteSpace(_sFilter))
_sFilter += " AND";
_sFilter += "(description LIKE '%" + _txtFilter1.Text.Trim() + "%')";
}
sdsTable1.FilterExpression = _sFilter;
Everything works until I clear the fields that leads to an empty filter, im such circumstances I expected to retrieve all the records but for some reason, in this case, the last recordset is kept and shown apparently without a reason.
I tried also to disable the SQLDataSource caching feature without luck:
EnableCaching="false"
I tried also to issue a Select command, again without luck:
sdsTable1.Select(DataSourceSelectArguments.Empty);
Where I'm wrong?
Your _sFilter property will be persisted across postbacks, so as you're only updating it when your filter text boxes are not empty it will remain at the last set value when you clear them. Putting a breakpoint in your code at the line _sdsTable1.FilterExpression = _sFilter; should confirm this.
To solve the issue, either clear the _sFilter property before rebuilding it in your event handler, or write an additional check:
if (string.IsNullOrWhiteSpace(_txtFilter1.Text.Trim()) & string.IsNullOrWhiteSpace(_txtFilter0.Text.Trim()) )
{
_sFilter = null;
}
Related
I have a gridview that has a textbox in one of cells in my aspx file.
After clicking the edit link in the row, I am able to get the control programatically in the rowdatabound event with this:
e.Row.FindControl("controlPlaceholder");
Using the edit index from the edit event works as well.
However, the control is only enabled on the first page of the gridview. On any other page, FindControl() returns null.
What could be the reason for this? Are there any potential solutions to this issue? I've looked for a solution but haven't had any luck with finding someone who has this particular problem.
Markup:
<asp:Panel ID="pnlAccountAssignment" runat="server" CssClass="clsDataPanel" meta:resourcekey="pnlAccountAssignmentResource1">
<asp:GridView ID="gvAccountAssignment" runat="server" AutoGenerateColumns="False"
AllowPaging="true" PageSize="25" OnRowDataBound="gvAccountAssignment_RowDataBound"
OnRowCancelingEdit="gvAccountAssignment_RowCancelingEdit" OnRowEditing="gvAccountAssignment_RowEditing"
OnRowUpdating="gvAccountAssignment_RowUpdating" OnPageIndexChanging="gvAccountAssignment_PageIndexChanging"
OnSorting="gvAccountAssignment_Sorting" AllowSorting="True" meta:resourcekey="gvAccountAssignmentResource1">
<RowStyle BackColor="White" ForeColor="Black" />
<HeaderStyle CssClass="clsGrayBkgCell" HorizontalAlign="Center" VerticalAlign="Bottom" />
<Columns>
...Other Columns...
<asp:TemplateField meta:resourcekey="TemplateFieldResource8">
<ItemStyle CssClass="clsNumber" HorizontalAlign="Left" VerticalAlign="Top" />
<EditItemTemplate>
<asp:TextBox ID="column13PlaceHolder" runat="server" CssClass="clsNormalLabel">
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblprevMonth" runat="server" CssClass="clsNormalLabel"></asp:Label>
</ItemTemplate>
<HeaderTemplate>
<asp:LinkButton runat="server" ID="hypSortGLBal" OnClick="hypSortGLBal_Click"></asp:LinkButton>
</HeaderTemplate>
</asp:TemplateField>
...Other Columns...
</Columns>
<PagerStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
<asp:HiddenField ID="hdnPrepPopulated" runat="server" />
</asp:Panel>
How do I send mltiple users message using a griview which should be connected to two tables namely login(from where usernames will be retrieved and shown) and then the second table message (where a message is to be stored for particular usernames). I have connected it to login but I am not able to insert values into message table. Message table has msg_id , username and message columns.
Here is the design:
.aspx
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataSourceID="SqlDataSource1"
onrowcommand="GridView2_RowCommand">
<Columns>
<asp:BoundField DataField="username" HeaderText="username"
SortExpression="username" />
<asp:BoundField DataField="password" HeaderText="password"
SortExpression="password" />
<asp:BoundField DataField="utype" HeaderText="utype" SortExpression="utype" />
<asp:BoundField DataField="ptype" HeaderText="ptype" SortExpression="ptype" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AutomobileConnectionString14 %>"
SelectCommand="SELECT * FROM [login] WHERE ([utype] LIKE '%' + #utype + '%')">
<SelectParameters>
<asp:Parameter DefaultValue="U" Name="utype" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
aspx.cs code
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("cc"))
{
TextBox txt1 = (TextBox)GridView2.FooterRow.FindControl("TextBox1");
foreach(GridView gr in GridView2.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("CheckBox1");
if (chk.Checked)
{
Object ob = GridView2.DataKeys[gr.RowIndex].Value;
}
now I am stuck her how can I insert values into other table message when it is already connected to Login table. Help me what I want to accomplish here is send message to checked users.
Try below :
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="userId"
OnRowCommand="GridView2_RowCommand" OnRowEditing="GridView2_RowEditing" OnRowUpdated="GridView2_RowUpdated" OnRowUpdating="GridView2_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label Text='<%# Eval("username") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="password" HeaderText="password"
SortExpression="password" />
<asp:BoundField DataField="utype" HeaderText="utype" SortExpression="utype" />
<asp:BoundField DataField="ptype" HeaderText="ptype" SortExpression="ptype" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label Text='<%# Eval("messgae") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMsg" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
On RowDataBound event to set the edit textbox for message by find control.
And refer to code for inline editing on check box click.
http://www.c-sharpcorner.com/UploadFile/9f0ae2/gridview-edit-delete-and-update-in-Asp-Net/
http://www.codeproject.com/Articles/23471/Editable-GridView-in-ASP-NET
I have a grid view in my aspx page. I have enabled paging also.
Paging is working fine when an ajax control is in page, but when I removed the ajax control paging is not working anymore. ie, on clicking page number 2 grid becomes empty.
What could be the possible reason? Please suggest a solution.
code
<asp:GridView ID="SitesGrid" runat="server" AllowPaging="True" AllowSorting="True" DataSourceID="SitesDataMgr" AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="3" CellSpacing="3" OnRowDataBound="viewSite_RowDataBound" class="tbl_blck gridtable clearfix" PageSize="4" EmptyDataText="No rows found">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="clientID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-ForeColor="White" SortExpression="ClientName">
<ItemTemplate>
<asp:Label ID="clientLabel" runat="server" Text='<%# Bind("ClientName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" HeaderStyle-ForeColor="White" SortExpression="SiteStatus">
<ItemTemplate>
<asp:Label ID="siteLabel" runat="server" Text='<%# Bind("SiteStatus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Details" HeaderStyle-ForeColor="White" >
<ItemTemplate>
<asp:LinkButton ID="viewSite" runat="server" OnClick="viewSite_click" CausesValidation="False" CommandName="Edit"
Text="View"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="SitesDataMgr" runat="server" ConvertNullToDBNull="True" OldValuesParameterFormatString="{0}" SelectMethod="GetAllSitesByUser" FilterExpression="ClientName LIKE '%{0}%'" TypeName="Creation.DataMgr">
<SelectParameters>
<asp:SessionParameter Name="createdUserID" Type="String" SessionField="strUserName" />
</SelectParameters>
<FilterParameters>
<asp:ControlParameter Name="ClientName" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:ObjectDataSource>
It looks like you have not added the SelectCount method to your ObjectDataSource.
This is required for the ObjectDatasource to correctly page your data.
Your select method needs the int parameters maximumRows and startRowIndex This is the default parameter names required for paging. if you do have them in. Please use them to filter your data.
I have this grid set up.... it all works totally fine... except one issue...
<asp:GridView runat="server"
ID="grdFacetsAssigned"
AllowPaging="false"
AllowSorting="True"
DataKeyNames="lngSystemFacet"
OnSelectedIndexChanging="grdFacetsAssigned_SelectedIndexChanging"
CssClass="table_scroll"
AutoGenerateColumns="False" GridLines="None"
ShowHeader="false" Width="500px"
OnSelectedIndexChanged="grdFacetsAssigned_SelectedIndexChanged"
ShowFooter="false" PagerSettings-Visible="false"
DataSourceID="SM_spStateUpdateReport_FacetAssignList"
OnRowCreated="grdFacetsAssigned_RowCreated">
<RowStyle CssClass="table_row" />
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lbllngSystemFacetID" runat="server"
Text='<%# Eval("lngSystemFacetID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="strSystemSystemFacet" SortExpression="strSystemSystemFacet"
ItemStyle-Width="50%" />
<asp:TemplateField ItemStyle-Width="30%" ItemStyle-HorizontalAlign="Center"
SortExpression="bolAssigned">
<ItemTemplate>
<asp:CheckBox ID="chkFacetAssigned" runat="server"
OnClientClick="alert(this.checked);"
OnCheckedChanged="chkFacetAssigned_CheckedChanged"
AutoPostBack="True" Checked='<%# Eval("bolAssigned") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="intOrder"
HeaderText="Display Order" ItemStyle-Width="20%">
<ItemTemplate>
<asp:Label ID="lblAssignedFacetOrder" runat="server"
Text='<%#DataBinder.Eval(Container.DataItem, "intOrder")%>'></asp:Label>
<asp:TextBox ID="txtAssignedFacetOrder" runat="server"
CssClass="gridview_input"
Text='<%#DataBinder.Eval(Container.DataItem, "intOrder")%>'
Visible="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle CssClass="table_selected_row" />
<AlternatingRowStyle CssClass="table_alternating_row" />
<EmptyDataRowStyle CssClass="table_empty" />
<EmptyDataTemplate>
No Data
</EmptyDataTemplate>
</asp:GridView>
When you click the chkFacetAssigned checkbox the appropriate event fires. The code works well from there. What happens though is when the checkbox is checked... if the row is not selected there are two postbacks that happen. The first postback is from the grid and the second postback is from the checkbox. Both postbacks cause the chkFacetAssigned_CheckedChanged event to be called- resulting in code running twice that should only run once. I should note that if the row is already selected (the row the checkbox is on) you do not see this extra postback. Someone please help.
There are no other event handlers registered or anything like this.
First line of your code. Remove the following.
OnSelectedIndexChanging="grdFacetsAssigned_SelectedIndexChanging"
Second Line
OnSelectedIndexChanged="grdFacetsAssigned_SelectedIndexChanged"
What I did for this was a workaround in the checkbox event handler...
if (Page.Request.Params["__EVENTTARGET"].IndexOf("chkFacetAssigned") < 1)
{
return;
}
This ensures that the event is ignored unless it is responding to a postback that was initiated by the checkbox and not the grid.
.NET 4 ASP.NET
I have a DetailsView that is displaying an entity framework record for a table that has a linked lookup table. I have an asp:BoundField with the datafield set as "linkedTable.Field" and it displays a value.
<asp:BoundField DataField="linkedTable.Field" HeaderText="linkedTable.Field"
SortExpression="linkedTable.Field" />
I am trying to use that value in an asp:TemplateField but when I try to get it using:
<asp:TemplateField HeaderText="Field" SortExpression="linkedTable.Field" >
<EditItemTemplate>
<asp:Label runat="server" ID="lblField" Text='<%# Bind("linkedTable.Field") %>' />
</EditItemTemplate>
</asp:TemplateField>
Nothing shows up in the label. I can change the Bind() to a field that is not part of the linked table and it works (i.e. the "ID" field). My problem is I don't understand why the linkedtable.Field value shows up in one context and not in the other.
FYI, my data connection is a EntityDataSource
<asp:EntityDataSource ID="edsNYSEDaily" runat="server"
ConnectionString="name=ServerDBEntities"
DefaultContainerName="ServerDBEntities" EntitySetName="tblNYSE"
EntityTypeFilter="tblNYSE" EnableUpdate="True" EnableFlattening="true"
AutoGenerateWhereClause="True" Select="" Where="">
<WhereParameters>
<asp:QueryStringParameter DefaultValue="0" Name="ID"
QueryStringField="ID" Type="Int32" />
</WhereParameters>
Let me know if you need any other information. I am stuck
Ok, discovered the problem:
Needed to add Include="linkedTable" to the EntityDataSource tag. Still not sure why it was even working in the <asp:DataBound /> tag.
Source for the answer: forums.asp.net
Copy of the text:
you should start here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.entitydatasource.include.aspx
notice that, you won't be able to Bind (I mean two-way data-binding) the related entities (see the remarks there).
and, you'd have to use a TemplateField for those properties.
see this example (I used the link table 'TableAB' for EntitySetName and included the other two):
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="EntityDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="IDA" HeaderText="IDA" SortExpression="IDA" />
<asp:BoundField DataField="IDB" HeaderText="IDB" SortExpression="IDB" />
<asp:TemplateField HeaderText="TableA Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("TableA.NameA") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TableB Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("TableB.NameB") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=ABLinkEntities"
DefaultContainerName="ABLinkEntities" EnableDelete="True" EnableFlattening="False"
EnableInsert="True" EnableUpdate="True" EntitySetName="TableABs" Include="TableA,TableB">
</asp:EntityDataSource>
you'll have to re-consider the updates and deletes, you could do them manually.