I have a function I've written that you pass in the gridview row, as well as what control type you're attempting to locate. It finds the control as intended, however, it finds it in the incorrect cell.
protected int GetCell(GridViewRow row, string strSection)
{
int intVal = 0;
for (int i = 0; i < row.Cells.Count; i++)
{
intVal = i;
if (strSection == "QueryRate")
{
DropDownList cmbQueryType = row.Cells[i].FindControl("cmbQueryType") as DropDownList;
if (cmbQueryType != null)
{
break;
}
}
else if (strSection == "Name")
{
TextBox txtName = row.Cells[i].FindControl("txtName") as TextBox;
if (txtName != null)
{
break;
}
}
}
return intVal;
}
From my understanding, and directly from the Microsoft page: Searches the current naming container for a server control with the specified id parameter.
So my question is, why is this seemingly finding the control is the wrong column? I can't hard code specific columns, because the columns that show vary based on the the datasource.
Per request, the gridview:
<TDWeb:PageGridView SkinID="pagegrid" EmptyDataText="No unmatched parameters." ID="gvUnmatched" runat="server" AllowSorting="True"
OnSorting="gvUnmatched_Sorting" AutoGenerateColumns="False" OnRowDataBound="gvUnmatched_RowDatabound" OnDataBound="gvUnmatched_DataBound"
OnPreRender="gvUnmatched_PreRender" OnPageIndexChanging="OnFilterUnmatched" DataKeyNames="InternalName"
ShowFooter="true" OnPageSizeChanged="gvUnmatched_PageSizeChanged">
<Columns>
<asp:TemplateField runat="server" ItemStyle-CssClass="c" FooterStyle-CssClass="c">
<HeaderTemplate>
<asp:Label runat="server" Text="Add" />
<asp:CheckBox runat="server" ID="ckbAddAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="ckbAdd" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" ItemStyle-CssClass="c">
<HeaderTemplate>
<asp:Label runat="server" Text="Ignore" />
<asp:CheckBox runat="server" ID="ckbIgnoreAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="ckbIgnore" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Name" SortExpression="Name" ItemStyle-CssClass="l">
<HeaderTemplate>
<asp:LinkButton runat="server" Text="Name" CommandName="Sort" CommandArgument="Name" />
<td:HelperBox ID="HelperBox5" runat="server" ToolTipText="Set the Name for this parameter. This value must be unique to the CAN Bus or ECU and is the value used throughout the DAP system to reference this parameter." />
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox runat="server" ID="txtName" Width="250" MaxLength="256" style="background-color:inherit" Text='<%# Bind("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" ItemStyle-CssClass="l" SortExpression="Description">
<HeaderTemplate>
<asp:LinkButton runat="server" Text="Description" CommandName="Sort" CommandArgument="Description" />
<td:HelperBox ID="HelperBox4" runat="server" ToolTipText="Set the Description for this parameter. This value is for informational purposes only. Not required." />
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDescription" Width="175" MaxLength="500"
TextMode="multiline" style="background-color:inherit" Text='<%# Bind("Description") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Length (bits)" SortExpression="LengthBits" ItemStyle-CssClass="r">
<ItemTemplate>
<asp:Label runat="server" ID="txtSizeBits" Text='<%# (int)Eval("LengthBits") + (int)Eval("LengthBytes") * 8 %>' style="background-color:inherit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" AccessibleHeaderText="SourceAddress" HeaderText="SA" SortExpression="Sources" ItemStyle-CssClass="r">
<ItemTemplate>
<asp:Label runat="server" ID="txtSources" Text='<%# Eval("SourceString") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" AccessibleHeaderText="ID" HeaderText="ID/Address" SortExpression="IDorAddress" ItemStyle-CssClass="r">
<ItemTemplate>
<asp:Label runat="server" ID="txtIDorAddress" Text='<%# Eval("IDorAddress") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Data Type" SortExpression="Datatype" ItemStyle-CssClass="l">
<ItemTemplate>
<asp:Label runat="server" ID="txtDatatype" Text='<%# Bind("Datatype") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" AccessibleHeaderText="QueryRate" ItemStyle-CssClass="r" SortExpression="QueryRate" HeaderText="Query Rate">
<HeaderTemplate>
<asp:Label runat="server" Text="Rate" />
<td:HelperBox ID="HelperBox9" runat="server" ToolTipText="Set the Query Type and Rate for this parameter (if applicable). If set, this value overrides the default Query set below." />
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblCANRate" Text='<%# Eval("QueryRateString", "{0} s") %>' Visible='<%# m_SelectedFile.ImportType == App_Code.DAPConfig.ParameterFileImport.EImportType.CANDBC || (m_SelectedFile.ImportType == App_Code.DAPConfig.ParameterFileImport.EImportType.J1939DBC && ((int)Eval("QueryRate")) > 0) %>' />
<asp:DropDownList runat="server" ID="cmbQueryType" style="background-color:inherit" Visible='<%# m_SelectedFile.ImportType != App_Code.DAPConfig.ParameterFileImport.EImportType.CANDBC && (m_SelectedFile.ImportType != App_Code.DAPConfig.ParameterFileImport.EImportType.J1939DBC || (int)Eval("QueryRate") <= 0) %>' />
<asp:Panel runat="server" id="pnlRate" style="display:none" ><asp:TextBox runat="server" ID="txtRate" Width="50" MaxLength="6" style="background-color:inherit" />s</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Category" ItemStyle-CssClass="l">
<HeaderTemplate>
<asp:Label runat="server" Text="Category" />
<td:HelperBox ID="HelperBox10" runat="server" ToolTipText="Set the Category with which to group this parameter, or create a new category." />
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList runat="server" ID="cmbCategory" style="background-color:inherit" >
<asp:ListItem Value="_New_" Text="Add New..." />
</asp:DropDownList>
<br />
<asp:TextBox Width="100" MaxLength="50" runat="server" ID="txtCategory" style="display:none;background-color:inherit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</TDWeb:PageGridView>
ok - turns out that calling row.cells(0).FindControl("") is the equivalent of calling row.FindControl("") because FindControl() operates within the current NamingContainer. And all the cells in a given row have the same NamingContainer, specifically {System.Web.UI.WebControls.GridViewRow}
If all you need is to determine the column index of a given control try this (pardon the VB):
Public Function getCellIndexByName(ByVal row As GridViewRow, ByVal ColumnName As String) As Integer
For ci As Integer = 0 To row.Cells.Count - 1
If CType(row.Cells(ci), DataControlFieldCell).ContainingField.ToString() = ColumnName Then
Return ci
End If
Next
Return -1
End Function
If you know the ID of the control that you are trying to find, you don't need to specify the cell. You can find it by looking in the whole row.
DropDownList cmbQueryType = row.FindControl("cmbQueryType") as DropDownList
This way you avoid the problem of incorrect cell index.
Related
I use a CalendarExtender of AjaxControlToolkit in a GridView and a TextBox. And from that TextBox I want to disable future dates.
I am trying below code
<asp:GridView ID="Gridview2" runat="server" AutoGenerateColumns="false" DataKeyNames="Sno" ShowFooter="true" OnRowCommand="Gridview2_RowCommand" CssClass="table table-bordered table-striped"
OnRowCancelingEdit="Gridview2_RowCancelingEdit" OnRowDeleting="Gridview2_RowDeleting" OnRowEditing="Gridview2_RowEditing" OnRowUpdating="Gridview2_RowUpdating" OnRowDataBound="Gridview2_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Sno" Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_sno1" runat="server" Text='<%#Eval("Sno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date of visit" ShowHeader="false">
<EditItemTemplate>
<asp:TextBox ID="Txt_update_DateofVisit1" runat="server" Text='<%# Eval("DateofVisit","{0:MM/dd/yyyy}") %>' CssClass="form-control"/>
<cc1:CalendarExtender ID="CalendarExtenderedit11" CssClass="Calendar" TargetControlID="Txt_update_DateofVisit1" Format="MM/dd/yyyy" runat="server"></cc1:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_DateofVisit1" runat="server" Text='<%# Eval("DateofVisit","{0:MM/dd/yyyy}") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_DateofVisit_add" runat="server" CssClass="form-control" />
<cc1:CalendarExtender ID="CalendarExtendere21" CssClass="Calendar" TargetControlID="txt_DateofVisit_add" Format="MM/dd/yyyy" runat="server"></cc1:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgbtnDelete_add" runat="server" CommandName="Delete" ImageUrl="~/img/grid_delete.png" Text="Edit" ToolTip="click here to delete" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd_add" runat="server" CommandName="AddNew" ImageUrl="~/img/grid_add.png" ToolTip="click here to add" CausesValidation="true" ValidationGroup="outadd" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below is my RowDataBound
protected void Gridview2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AjaxControlToolkit.CalendarExtender CalendarExtendere21 = (AjaxControlToolkit.CalendarExtender)Gridview2.FooterRow.FindControl("CalendarExtendere21");
CalendarExtendere21.EndDate = DateTime.Now;
// CalendarExtendere21.StartDate = DateTime.Now;
}
}
I get below error:
Object reference not set to an instance of an object.
just use parameter e to find out control in grid
if (e.Row.RowType == DataControlRowType.Footer)
{
AjaxControlToolkit.CalendarExtender CalendarExtendere21 =
(e.Row.FindControl("CalendarExtendere21") as AjaxControlToolkit.CalendarExtender);
}
and don't forget to check for null
I have grid with text box for filter data on header.I have button outside the grid.I am using this gridview for filtering the grid by some columns. When I click on button I want to get value from text box and dropdownlist on codebehind.cs, below is my webform.aspx code of gridview,
<asp:Button ID="btngetLocationDate" runat="server" Text="Get Filtered Data" OnClick="getTextBoxValue"></asp:Button>
<asp:GridView ID="TrackerGrid" runat="server" BackColor="#CCCCCC" AllowPaging="True" AutoGenerateColumns="false">
<AlternatingRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<Columns>
<asp:TemplateField HeaderText="User ID" SortExpression="User ID">
<ItemTemplate>
<asp:Label ID="lbluserid" runat="server" Text='<%# Eval("User ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Name">
<HeaderTemplate>
Full Name:
<asp:DropDownList ID="ddlfullName" runat="server" AutoPostBack="true" OnSelectedIndexChanged="onselectDropdown">
<asp:ListItem Text="ALL" Value="ALL" Selected="True"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("Full Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile Number">
<HeaderTemplate>
Mobile Number:
<asp:TextBox ID="txtMobilenumber" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblmobile" runat="server" Text='<%# Eval("Mobile Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Address">
<HeaderTemplate>
Email Id:
<asp:TextBox ID="txtemail" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%# Eval("Email ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Longitude">
<HeaderTemplate>
<asp:Label ID="lbllng" runat="server" Text="Longitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllongi" runat="server" Text='<%# Eval("Longitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lattitude">
<HeaderTemplate>
<asp:Label ID="lbllat" runat="server" Text="Lattitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllatti" runat="server" Text='<%# Eval("Lattitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activated On">
<HeaderTemplate>
<asp:Label ID="lbldevices" runat="server" Text="Activated On"></asp:Label></br>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbldevice" runat="server" Text='<%# Eval("Activated On") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location DateTime" SortExpression="Location DateTime">
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="Location DateTime"></asp:Label></br>
<asp:Label ID="lblStartDate" runat="server" AssociatedControlID="txtStartDate" Text="Start Date"></asp:Label>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarStartDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtStartDate" popupbuttonid="imgPopup1"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup1" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</br>
<asp:Label ID="lblEndDate" runat="server" Text="End Date" AssociatedControlID="txtEndDate"></asp:Label>
<asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarEndDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtEndDate" popupbuttonid="imgPopup2"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup2" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblDatetime" runat="server" Text='<%# Eval("Location DateTime") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and I am getting texbox value in codebehind code.
protected void getTextBoxValue(object sender, EventArgs e)
{
DropDownList ddlfullname = (TrackerGrid.HeaderRow.FindControl("ddlfullName") as DropDownList);
string selectedValue = ddlfullname.SelectedItem.Text;
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox);
string mobile = mobilenumber.Text;
TextBox email = TrackerGrid.HeaderRow.FindControl("txtemail") as TextBox;
string emailid = email.Text;
TextBox staloc = TrackerGrid.HeaderRow.FindControl("txtStartDate") as TextBox;
string startlocatdate = staloc.Text;
TextBox endloc = TrackerGrid.HeaderRow.FindControl("txtEndDate") as TextBox;
string endlocadate = endloc.Text;
}
I am getting empty value when I debugging this code.I think my code is correct but how i am not getting value of textboxes, i don't understand. Please help me for solving my issue.
Thanks in advance.
You probably did not wrap the DataBind() of the Gridview inside an IspostBack check. If you do not then the values will be rested by the DataBind instead of being saved with ViewState.
protected void Page_Load(object sender, EventArgs e)
{
//not here
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
if (IsPostBack == false)
{
//but inside an ispostback check
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
}
}
In my web page, I have an LinkButton inside FooterTemplate, when I Add new row in GridView by using RowCommand. LinkButton do partial postback but my page loses its current scroll position and return scroll to top of the page. How should I maintain my page scroll position when I add new Item in my GridView.
Below is my screen output:
Below is my page code:
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Invoice.aspx.cs" Inherits="RSMS.Users.Invoice" %>
<asp:UpdatePanel ID="upItemDetail" runat="server">
<ContentTemplate>
<asp:GridView
ID="gvItemDetail"
runat="server"
Width="100%"
ShowHeaderWhenEmpty="true"
AutoGenerateColumns="false"
EmptyDataText="No Data Found!"
ShowFooter="False"
BorderStyle="None"
CellPadding="3"
GridLines="Horizontal"
SkinID="AHGridView"
OnRowCommand="gvItemDetail_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Item ID">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("Item_Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtItemName"
runat="server"
placeholder="Item Name"
CssClass="form-control"></asp:TextBox>
</div>
<asp:HiddenField ID="hdnItemID" runat="server" Value="" ClientIDMode="Static" />
<div id="AutoCompleteItem"></div>
<%--<asp:RequiredFieldValidator
ID="rfvItemName"
runat="server"
ControlToValidate="txtItemName"
ErrorMessage="Item Name must be enter."
Display="None">
</asp:RequiredFieldValidator>--%>
<ajaxToolkit:AutoCompleteExtender
ID="acetxtItemName"
runat="server"
ServiceMethod="GetItemID"
ServicePath="~/ApplicationWebService.asmx"
TargetControlID="txtItemName"
MinimumPrefixLength="1"
UseContextKey="false"
CompletionInterval="0"
EnableCaching="true"
CompletionSetCount="30"
FirstRowSelected="true"
CompletionListElementID="AutoCompleteItem"
OnClientItemSelected="ItemSelected">
</ajaxToolkit:AutoCompleteExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtItemName"
runat="server"
placeholder="Item Name"
TabIndex="5"
CssClass="form-control"></asp:TextBox>
</div>
<asp:HiddenField ID="hdnItemID" runat="server" Value="" ClientIDMode="Static" />
<div id="AutoCompleteItem"></div>
<%--<asp:RequiredFieldValidator
ID="rfvItemName"
runat="server"
ControlToValidate="txtItemName"
ErrorMessage="Item Name must be enter."
Display="None">
</asp:RequiredFieldValidator>--%>
<ajaxToolkit:AutoCompleteExtender
ID="acetxtItemName"
runat="server"
ServiceMethod="GetItemID"
ServicePath="~/ApplicationWebService.asmx"
TargetControlID="txtItemName"
MinimumPrefixLength="1"
UseContextKey="false"
CompletionInterval="0"
EnableCaching="true"
CompletionSetCount="30"
FirstRowSelected="true"
CompletionListElementID="AutoCompleteItem"
OnClientItemSelected="ItemSelected">
</ajaxToolkit:AutoCompleteExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sales Price">
<ItemTemplate>
<asp:Label ID="lblItemSalesPrice" runat="server" Text='<%# Eval("Sale_Price") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtSalesPrice"
runat="server"
placeholder="Sales Price"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeSalesPrice" runat="server"
TargetControlID="txtSalesPrice"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvPrice"
runat="server"
ControlToValidate="txtPurchasePrice"
ErrorMessage="Purchase Price must be in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtSalesPrice"
runat="server"
placeholder="Sales Price"
Text='<%# Eval("Sale_Price") == null ? "0" : Eval("Sale_Price") %>'
TabIndex="6"
ClientIDMode="Static"
CssClass="form-control"></asp:TextBox>
<asp:HiddenField ID="hdnPurchase_Price" runat="server" ClientIDMode="Static" Value="0" />
<%--<ajaxToolkit:FilteredTextBoxExtender ID="ftbeSalesPrice" runat="server"
TargetControlID="txtSalesPrice"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>--%>
<%--<asp:RequiredFieldValidator
ID="rfvPurchasePrice"
runat="server"
ControlToValidate="txtPurchasePrice"
ErrorMessage="Purchase Price must be in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item QTY">
<ItemTemplate>
<asp:Label ID="lblItemQTY" runat="server" Text='<%# Eval("Item_Qty") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="txtItemQuantity"
runat="server"
placeholder="Quantity"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeQuantity" runat="server"
TargetControlID="txtItemQuantity"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvQuantity"
runat="server"
ControlToValidate="txtItemQuantity"
ErrorMessage="Item Quantity must be enter in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox
ID="txtItemQuantity"
runat="server"
placeholder="Quantity"
Text='<%# Eval("Item_Qty") == null ? "0" : Eval("Item_Qty") %>'
TabIndex="7"
CssClass="form-control"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbeQuantity" runat="server"
TargetControlID="txtItemQuantity"
FilterType="Numbers"></ajaxToolkit:FilteredTextBoxExtender>
<%--<asp:RequiredFieldValidator
ID="rfvQuantity"
runat="server"
ControlToValidate="txtItemQuantity"
ErrorMessage="Item Quantity must be enter in numbers."
Display="None">
</asp:RequiredFieldValidator>--%>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UOM">
<ItemTemplate>
<asp:Label ID="lblUOM" runat="server" Text='<%# Eval("Item_UOM") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList
ID="ddlUOM"
runat="server"
CssClass="ah-border-less"
AutoPostBack="true">
<asp:ListItem Selected="True" Value="0">Select UOM</asp:ListItem>
<asp:ListItem Value="1">GM</asp:ListItem>
<asp:ListItem Value="2">KG</asp:ListItem>
<asp:ListItem Value="3">PCS</asp:ListItem>
<asp:ListItem Value="4">DZ</asp:ListItem>
<asp:ListItem Value="5">BOX</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList
ID="ddlUOM"
runat="server"
TabIndex="8"
CssClass="ah-border-less">
<asp:ListItem Selected="True" Value="0">Select UOM</asp:ListItem>
<asp:ListItem Value="GM">GM</asp:ListItem>
<asp:ListItem Value="KG">KG</asp:ListItem>
<asp:ListItem Value="PCS">PCS</asp:ListItem>
<asp:ListItem Value="DZ">DZ</asp:ListItem>
<asp:ListItem Value="BOX">BOX</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Price">
<ItemTemplate>
<asp:Label ID="lblTotalPrice" Text='<%# Eval("Total_Price") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalPrice" runat="server" Text='<%# Eval("Total_Price") == null ? "0" : Eval("Total_Price") %>'></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="itemAdd" ClientIDMode="AutoID" CommandName="Add" runat="server" TabIndex="9">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
Aspx.cs Code:
protected void gvItemDetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
HiddenField itemID = (HiddenField)gvItemDetail.FooterRow.FindControl("hdnItemID");
HiddenField itemPurchasePrice = (HiddenField)gvItemDetail.FooterRow.FindControl("hdnPurchase_Price");
TextBox itemName = (TextBox)gvItemDetail.FooterRow.FindControl("txtItemName");
TextBox itemSalesPrice = (TextBox)gvItemDetail.FooterRow.FindControl("txtSalesPrice");
TextBox itemQTY = (TextBox)gvItemDetail.FooterRow.FindControl("txtItemQuantity");
DropDownList itemUOM = (DropDownList)gvItemDetail.FooterRow.FindControl("ddlUOM");
Label itemTotalPrice = (Label)gvItemDetail.FooterRow.FindControl("lblTotalPrice");
Decimal dcmTotalPrice = (Convert.ToDecimal(itemSalesPrice.Text.Trim()) * Convert.ToDecimal(itemQTY.Text.Trim()));
Decimal dcmPurchasePrice = (Convert.ToDecimal(itemPurchasePrice.Value.Trim()) * Convert.ToDecimal(itemQTY.Text.Trim()));
DataTable dt = (DataTable)HttpContext.Current.Session["dtInvoiceItemDetail"];
//dt.Rows[0].Delete();
dt.Rows.Add(itemID.Value.Trim(),
itemName.Text.Trim(),
itemSalesPrice.Text.Trim(),
itemQTY.Text.Trim(),
itemUOM.SelectedValue.ToString().Trim(),
dcmTotalPrice,
dcmPurchasePrice
);
dt.AcceptChanges();
gvItemDetail.DataSource = dt;
gvItemDetail.DataBind();
gvItemDetail.Rows[0].Visible = false;
HttpContext.Current.Session["dtInvoiceItemDetail"] = dt;
lblCalculateTotal.Text = (Convert.ToDecimal(dt.AsEnumerable()
.Sum(x => Convert.ToDecimal(x["Total_Price"])))).ToString();
commission = ((Convert.ToDecimal(lblCalculateTotal.Text.Trim()) - Convert.ToDecimal(dt.AsEnumerable()
.Sum(x => Convert.ToDecimal(x["Purchase_Price"])))) * 10) / 100;
}
gvItemDetail.FooterRow.Focus();
}
What I've tried:
Maintain Panel Scroll Position On Partial Postback ASP.NET
Re: Update Panel Scrolling Issue
Maintain Panel Scroll Position On Postback in ASP.NET
page jumps to top
how to retain browser scroll position for Dynamic Control Events
I've found my solution that when I remove gvItemDetail.FooterRow.Focus(); code my page maintain its scroll position. Thanks for all of your comments.
I face this issue before. My resolution is to add maintainScrollPositionOnPostBack="true" in the web.config file
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<pages maintainScrollPositionOnPostBack="true" /> //this will keep current position after postback
</system.web>
I´m using a DetailsView but when updating, I cannot get the OldValues because the DetailsViewUpdateEventArgs.OldValues of ItemUpdating event is always empty. The NewValues has the values ok.
Note: I´m not using a datasource component in my application (SqlDataSource, ObjectDataSource, EntityDataSource, etc.). In this case should I do something manually?
Any ideas will be welcome!
Thanks!
Complementing the information:
I´m using ASP.NET 4.0 (WebForms)
A snippet of code that I believe to be relevant below:
<asp:DetailsView ID="customerDetails" runat="server" AutoGenerateRows="False" EmptyDataText="No data..."
meta:resourcekey="customerDetails"
onitemdeleting="customerDetails_ItemDeleting"
oniteminserting="customerDetails_ItemInserting"
onitemupdating="customerDetails_ItemUpdating"
onmodechanging="customerDetails_ModeChanging"
CssClass="customerDetails" DataKeyNames="CustomerID">
<FooterTemplate>
<asp:LinkButton ID="lnkNew" Text="New" ToolTip="New Customer" CommandName="New" meta:resourcekey="lnkNew" runat="server" />
</FooterTemplate>
<EmptyDataTemplate>
<p><asp:Label ID="lblNoDataHasBeenFound" Text="No data has been found." meta:resourcekey="lblNoDataHasBeenFound" runat="server" /></p>
<asp:LinkButton ID="lnkNew" Text="New" ToolTip="New Customer" CommandName="New" meta:resourcekey="lnkNew" runat="server" />
</EmptyDataTemplate>
<Fields>
<%--CustomerID--%>
<asp:TemplateField HeaderStyle-CssClass="detailsHeader" ItemStyle-CssClass="detailsField">
<HeaderTemplate>
<asp:Label ID="ltrCustomerIdLabel" meta:resourcekey="ltrCustomerId" Text="CustomerID:" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCustomerId" Text='<%# Eval("CustomerID") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCustomerId" Text='<%# Eval("CustomerID") %>' runat="server" />
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtCustomerId" Text='<%# Bind("CustomerID") %>' MaxLength="5" width="50px" runat="server" />
<cc1:DataAnnotationsValidator ID="CustomerIdValidator" Type="String" runat="server" ControlToValidate="txtCustomerId" PropertyName="CustomerID" Text="*" SourceType="DataLayerPOCO.Customer, DataLayerPOCO" CssError="validationError" Display="None"/>
</InsertItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<%--CompanyName--%>
<asp:TemplateField HeaderStyle-CssClass="detailsHeader" ItemStyle-CssClass="detailsField">
<HeaderTemplate>
<asp:Literal ID="ltrCompanyNameLabel" meta:resourcekey="ltrCompanyName" Text="Company Name:" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Literal ID="ltrCompanyName" Text='<%# Eval("CompanyName") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCompanyName" Text='<%# Bind("CompanyName") %>' MaxLength="40" Width="310px"
runat="server" />
<cc1:DataAnnotationsValidator ID="CompanyNameValidator" Type="String" runat="server" ControlToValidate="txtCompanyName" PropertyName="CompanyName" Text="*" SourceType="DataLayerPOCO.Customer, DataLayerPOCO" CssError="validationError" Display="None"/>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtCompanyName" Text='<%# Bind("CompanyName") %>' MaxLength="40" Width="310px"
runat="server" />
<cc1:DataAnnotationsValidator ID="CompanyNameValidator" Type="String" runat="server" ControlToValidate="txtCompanyName" PropertyName="CompanyName" Text="*" SourceType="DataLayerPOCO.Customer, DataLayerPOCO" CssError="validationError" Display="None"/>
</InsertItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
...
...
other fields goes here
...
...
<%--Edit/Insert--%>
<asp:TemplateField HeaderStyle-CssClass="detailsHeader" ItemStyle-CssClass="detailsField">
<ItemTemplate>
<asp:ImageButton ID="imgEdit" ImageUrl="~/img/pencil.png" meta:resourcekey="imgEdit" AlternateText="Edit" ToolTip="Edit Customer" CommandName="Edit" runat="server" CausesValidation="false"/>
<asp:ImageButton ID="imgDelete" ImageUrl="~/img/delete.png" meta:resourcekey="imgDelete" AlternateText="Delete" ToolTip="Delete Customer" CommandName="Delete" OnClientClick="return confirmDelete();" runat="server" CausesValidation="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgUpdate" ImageUrl="~/img/accept.png" meta:resourcekey="imgUpdate" AlternateText="Update" ToolTip="Update Customer" CommandName="Update" runat="server" />
<asp:ImageButton ID="imgCancel" ImageUrl="~/img/cancel.png" meta:resourcekey="imgCancel" AlternateText="Cancel" ToolTip="Cancel Edit" CommandName="Cancel" runat="server" CausesValidation="false"/>
</EditItemTemplate>
<InsertItemTemplate>
<asp:ImageButton ID="imgSave" ImageUrl="~/img/disk.png" meta:resourcekey="imgSave" AlternateText="Save" ToolTip="Save Customer Data" CommandName="Insert" runat="server" CausesValidation="true"/>
<asp:ImageButton ID="imgCancelInsert" ImageUrl="~/img/cancel.png" meta:resourcekey="imgCancelInsert" AlternateText="Cancel" ToolTip="Cancel Insert" CommandName="Cancel" runat="server" CausesValidation="false"/>
</InsertItemTemplate>
</asp:TemplateField>
<Fields>
</asp:DetailsView>
The event ItemUpdating is like below:
protected void customerDetails_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
repository = repository ?? new NorthwindRepositoryEF();
string id = e.Keys["CustomerID"] as string;
DataLayerPOCO.Customer customer = repository.GetCustomer(id);
string companyName = (string)e.NewValues["CompanyName"];
string contactName = (string)e.NewValues["ContactName"];
string contactTitle = (string)e.NewValues["ContactTitle"];
string address = (string)e.NewValues["Address"];
string city = (string)e.NewValues["City"];
string region = (string)e.NewValues["Region"];
string postalCode = (string)e.NewValues["PostalCode"];
string country = (string)e.NewValues["Country"];
string phone = (string)e.NewValues["Phone"];
string fax = (string)e.NewValues["Fax"];
// Update Customer with the new data
customer.CompanyName = companyName;
customer.ContactName = contactName;
customer.ContactTitle = contactTitle;
customer.Address = address;
customer.City = city;
customer.Region = region;
customer.PostalCode = postalCode;
customer.Country = country;
customer.Phone = phone;
customer.Fax = fax;
repository.UpdateCustomer(customer);
repository.Save();
//---
customerDetails.ChangeMode(DetailsViewMode.ReadOnly);
BindCustomerDetails();
BindCustomersList();
}
The problem is that if I want to handle the old values, I can´t:
this, evaluates to 0:
int oldValuesCount = e.OldValues.Count;
and this, evaluates to null, even if I alter the value to a new one:
string companyNameOld = e.OldValues["CompanyName"] as string;
It seems the old values are only populated when you have a data source bounded declaratively.
You have two workarounds in this case:
Save any old values you may need in ViewState programtically and retrieve it when you want it. This save a trip to the database.
A better option would to use the customer variable that you define in OnItemUpdating as it queries information from the database and contains all the old values.
Hope it helps.
I have label within a DetailsView.
I need to change Text property of this Label inside the DetailsView after event ItemInserted has been trigged.
Script does not throws any error, but the Label does not change its text property.
Any ideas what I am doing wrong?
Thanks for your time!
Markup:
<asp:DetailsView ID="uxInsertAuthorInput" runat="server" AutoGenerateRows="False"
DataKeyNames="AuthorId" DataSourceID="EntityDataSourceCreateAuthor" DefaultMode="Insert"
OnItemInserting="uxInsertAuthor_ItemInserting" OnItemInserted="uxInsertAuthorInput_ItemInserted">
<Fields>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemTemplate>
<asp:Label ID="uxFirstNameDisplayer" runat="server" Text='<%# Bind("FirstName") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxFirstNameInput" runat="server" Text='<%# Bind("FirstName") %>' />
<asp:RequiredFieldValidator ID="uxRequiredFieldValidatorFirstName" runat="server"
ControlToValidate="uxFirstNameInput" ErrorMessage="First Name Field is required">*</asp:RequiredFieldValidator>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemTemplate>
<asp:Label ID="uxLastNameDisplayer" runat="server" Text='<%# Bind("LastName") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxLastNameInput" runat="server" Text='<%# Bind("LastName") %>' />
<asp:RequiredFieldValidator ID="uxRequiredFieldValidatorLastName" runat="server"
ControlToValidate="uxLastNameInput" ErrorMessage="Last Name Field is required">*</asp:RequiredFieldValidator>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserId" SortExpression="UserId">
<InsertItemTemplate>
<asp:DropDownList ID="uxUserListSelector" runat="server" />
<asp:Label ID="uxAllert" runat="server" Text="Label" />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Profile" SortExpression="ContentAuthor">
<ItemTemplate>
<asp:Label ID="uxContentAuthorDisplayer" runat="server" Text='<%# Bind("ContentAuthor") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxContentAuthorInput" runat="server" Text='<%# Bind("ContentAuthor") %>' />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NoteInternal" SortExpression="NoteInternal">
<ItemTemplate>
<asp:Label ID="uxNoteInternalDisplayer" runat="server" Text='<%# Bind("NoteInternal") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxNoteInternalInput" runat="server" Text='<%# Bind("NoteInternal") %>' />
</InsertItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
Code-behind:
protected void uxInsertAuthorInput_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
String FirstName = e.Values["FirstName"].ToString();
String LastName = e.Values["LastName"].ToString();
uxMessageDisplayer.Text = string.Format("Author: {0} {1} has been added.", FirstName, LastName);
// problem is here:
Label myAllert = (Label)uxInsertAuthorInput.FindControl("uxAllert");
myAllert.Text = "TEST";
}
you need to use ItemUpdated event of detailsview rather than ItemInserted event
ItemUpdated: Occurs when an Update button within a DetailsView control is clicked, but after the update operation. from here
I am sure this will resolve issue 100%