invalid postback event instead of dropdown to datagrid - asp.net

I faced with funny situation. I created a page which is having some value, I set these value and control my post back event also. The problem is happening when I change a component index(ex reselect a combobox which is not inside my datagrid) then I dont know why without my page call the Page_Load it goes to create a new row in grid function and all of my parameter are null! I am just receiving null exception.
So in other word I try to explain the situation:
when I load my page I am initializing some parameter. then everything is working fine. in my page when I change selected item of my combo box, page suppose to go and run function related to that combo box, and call page_load, but it is not going there and it goes to rowcreated function.
I am trying to illustrate part of my page.
Please help me because I am not receiving any error except null exception and it triger wrong even which seems so complicated for me.
public partial class W_CM_FRM_02 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack && !loginFail)
return;
InitializeItems();
}
}
private void InitializeItems()
{
cols = new string[] { "v_classification_code", "v_classification_name" };
arrlstCMMM_CLASSIFICATION = (ArrayList)db.Select(cols, "CMMM_CLASSIFICATION", "v_classification_code <> 'N'", " ORDER BY v_classification_name");
}
}
protected void DGV_RFA_DETAILS_RowCreated(object sender, GridViewRowEventArgs e)
{
//db = (Database)Session["oCon"];
foreach (DataRow dr in arrlstCMMM_CLASSIFICATION)
((DropDownList)DGV_RFA_DETAILS.Rows[index].Cells[4].FindControl("OV_RFA_CLASSIFICATION")).Items.Add(new ListItem(dr["v_classification_name"].ToString(), dr["v_classification_code"].ToString()));
}
protected void V_CUSTOMER_SelectedIndexChanged(object sender, EventArgs e)
{
if (V_CUSTOMER.SelectedValue == "xxx" || V_CUSTOMER.SelectedValue == "ddd")
V_IMPACTED_FUNCTIONS.Enabled = true;
}
}
my form:
<%# Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="W_CM_FRM_02.aspx.cs"
Inherits="W_CM_FRM_02" Title="W_CM_FRM_02" enableeventvalidation="false" EnableViewState="true"%>
<td>Project name*</td>
<td><asp:DropDownList ID="V_CUSTOMER" runat="server" AutoPostBack="True"
onselectedindexchanged="V_CUSTOMER_SelectedIndexChanged" /></td>
<td colspan = "8">
<asp:GridView ID="DGV_RFA_DETAILS" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="1" ForeColor="#333333" GridLines="None" OnRowDeleting="grvRFADetails_RowDeleting"
Width="100%" Style="text-align: left"
onrowcreated="DGV_RFA_DETAILS_RowCreated">
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="ON_RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="RFA/RAD/Ticket No*">
<ItemTemplate>
<asp:TextBox ID="OV_RFA_NO" runat="server" Width="120"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

Hi remove enableeventvalidation="false" EnableViewState="true" from your page directive.

Related

ASP.NET - Finding Label Control in a GridView

I'm having a problem trying to find a label control that is inside a GridView.
Please see my codes below:
<asp:GridView ID="MyGridView" runat="server">
<Columns>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDate" MaxLength="10" Width="70" />
<asp:ImageButton ID="imgScoreDate" runat="server" ImageUrl="~/images/calendar.gif" />
<ajaxtoolkit:CalendarExtender ID="txtDate_CalendarExtender" runat="server" Enabled="True" Format="MM/dd/yyyy" TargetControlID="txtDate" PopupButtonID="imgDate" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my .cs file:
protected void LoadGridView()
{
//Do something else
foreach (GridViewRow row in MyGridView.Rows)
{
//Tried A
System.Web.UI.WebControls.Label lblName = row.FindControl("lblName") as System.Web.UI.WebControls.Label;
lblName.Text = "Name";
//Tried B
((System.Web.UI.WebControls.Label)row.FindControl("lblName")).Text = "Name";
}
}
I debug this code and it seems to work fine because my breakpoint is being hit each time the debugger runs. It even loops through my foreach block the same count as to how many rows my GridView has.
But I don't understand why my lblName control doesn't get the "Name" text as a value? Am I missing anything here? I tried both //Tried A and //Tried B methods but they both doesn't update my label's text.
Any help would be appreciated!
Thanks! Cheers!
You want to call LoadGridView inside PreRender. Basically, you want to call it after GridView is bound with data.
protected void Page_PreRender(object sender, EventArgs e)
{
LoadGridView();
}
Look at PreRender event of ASP.NET Page Life Cycle.
On your gridview add:
<asp:GridView OnRowDataBound="MyGridView_RowDataBound" ... />
Then define MyGridView_RowDataBound:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
Label l = (Label) e.Row.FindControl("lblName");
}
What I think is happening is the control is not recreated server side in its current spot.
try this
on .aspx page
<asp:GridView ID="MyGridView" runat="server"
onrowdatabound="MyGridView_RowDataBound" .../>
code behind ::
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGridView();
}
}
void LoadGridView()
{
DataTable dt = new DataTable();
// dt= call ur database method to get data
MyGridView.DataSource = dt;
MyGridView.DataBind();
}
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_Name = (Label)e.Row.FindControl("lblName");
lbl_Name.Text = "Name";
}
}
cheers!

Page Load not firing when input control placed in an asp GridView

I have a gridview which displays product information on the index page of my site for a user. I want to extend this to allow the user to tick a checkbox if they have reviewed a product.
However, after adding the check box column into my gridview template, when i try to search multiple times the Page_Load event of my index page stops firing, this causes an issue as some of the events further down the execution tree require the object that is initialised at page load.
The problem seems to be that placing any asp input control inside the gridview is somehow preventing Page_Load from firing before the DataSources OnSelecting and OnSelected and the Grids OnRowDataBound events but i can't see why.
Here is my sample code, I can't see what I'm doing wrong here.
Index.aspx.cs
private ProductSearch productSearch
protected void Page_Load(object sender, EventArgs e)
{
productSearch = new ProductSearch(GetSearchParameters());
productSearch.PageLoad()
}
protected void ProductsSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["searchParams"] = productSearch.GetSearchParams();
}
protected void ProductsSelected(object sender, ObjectDataSourceStatusEventArgs e)
{
productSearch.SetExportToCsvButton();
}
protected void ProductsPageIndexChanging(object sender, GridViewPageEventArgs e)
{
dgProducts.PageIndex = e.NewPageIndex;
}
protected void ProductsOnRowDataBound(object sender, GridViewRowEventArgs e)
{
productSearch.ProductsRowDataBound(e.Row);
}
Index.aspx
<%# Page Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Web.Admin.Index" %>
<asp:Content ContentPlaceHolderID="DataFrame" runat="server">
<asp:GridView ID="dgProducts" runat="server" AllowPaging="True" AllowSorting="True" EnableViewState="False"
AutoGenerateColumns="False" DataSourceID="dsProducts" PagerSettings-Position="TopAndBottom" DataKeyNames="ProductNo, KitID"
OnPageIndexChanging="ProductsPageIndexChanging" OnRowDataBound="ProductsOnRowDataBound"
EmptyDataText="There are no products matching your search." meta:resourcekey="dgProducts" onrowcreated="ProductsRowCreated">
<HeaderStyle Font-Size="Small" />
<Columns>
<asp:TemplateField HeaderText="Reviewed">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkReviewed" class="reviewedCheckbox" Checked="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns
</asp:GridView>
<asp:ObjectDataSource ID="dsProducts" runat="server" EnablePaging="True" SelectMethod="ProductAndKitSearchByParams"
TypeName="ProductSearchController.ProductSearch" onselecting="ProductsSelecting" SortParameterName="SortParameter"
SelectCountMethod="SelectVirtualCount" OnSelected="ProductsSelected">
<SelectParameters>
<asp:Parameter ConvertEmptyStringToNull="true" DefaultValue="" Name="searchParams" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
</asp:Content>
Check you master page contentplaceholderid and provide it in content page like this:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"></asp:Content>
and also check your content page codebehind file name should be same as mention in page directives.

Radio list with SelectedIndexChanged not firing inside radgrid

I have a user control that contains a radio list that on SelectIndexChanged it updates a drop down.
I put together a basic page and add the user control to the page it works fine but when I move the control to inside a radgrid it doesn't work, it will post back but never call the SelectIndexChanged event.
I've pulled up 2 previous questions on this Q. 1 and Q. 2 which say that OnSelectedIndexChanged needed to be set in the aspx page. My issue is that the control doesn't exist in the aspx page and is created later so that solution does not work for me.
Working code
working.aspx
<TT:ToolTipControl ID="ToolTipEdit" runat="server" />
working.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
ToolTipEdit.getEditToolTip("POL_TERM_CD", "DataPolTermDropDownlistEdit");
}
User Control
userControl.ascx.cs
public void getEditToolTip(string fieldName, string ddlName)
{
DataPolTermRadioListBox ccPolTermRadioListBox = new DataPolTermRadioListBox(); //custom radio list
ccPolTermRadioListBox.ID = "PolTermRadioListBox";
ccPolTermRadioListBox.AutoPostBack = true;
ccPolTermRadioListBox.SelectedIndexChanged += new System.EventHandler(updateParent);
ToolTip.Controls.Add(ccPolTermRadioListBox);
}
Broken Code
brokenPage.aspx
<telerik:RadGrid ID="rgState" Skin="WebBlue" runat="server" OnNeedDataSource="rgState_NeedDataSource"
AutoGenerateColumns="False" OnPreRender="rgState_PreRender">
<MasterTableView DataKeyNames="wrtnStPolId" AllowAutomaticUpdates="false" AllowAutomaticDeletes="true"
AllowAutomaticInserts="false" CommandItemDisplay="Top" AllowMultiColumnSorting="True"
EditMode="InPlace" GroupLoadMode="Server" Caption="State(s) and Exposure(s)">
<Columns>
<telerik:GridTemplateColumn AllowFiltering="false" HeaderText="Pol Type Nstd" SortExpression="nonStdPolTypeCd"
UniqueName="nonStdPolTypeCd">
<ItemTemplate>
<asp:Label ID="lblNonStdPolTypeCd" runat="server" align="center" Text='<%#DataBinder.Eval(Container.DataItem, "nonStdPolTypeCd")%>' />
</ItemTemplate>
<EditItemTemplate>
<cc1:DataNonStdTypeCdDropDownList ID="ddlNonStdTypeCd" runat="server" ClientIDMode="Predictable">
</cc1:DataNonStdTypeCdDropDownList>
<TT:ToolTipControl ID="ttcNonStdPolTypeCdEdit" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
brokenPage.aspx.cs
protected void rgState_PreRender(object sender, EventArgs e)
{
RadGrid rgExpMod = (RadGrid)sender;
foreach (GridDataItem row in rgExpMod.Items)
{
GridDataItem gdiItem = (GridDataItem)row;
if (row.FindControl("ttcNonStdPolTypeCdEdit") != null)
{
DropDownList ddl = (DropDownList)row.FindControl("ddlNonStdTypeCd");
ddl.ID += row.RowIndex;
ddl.SelectedIndex = 2;
NCCI.PDC.Web.Controls.ucToolTip ttcNonStdPolTypeCdEdit = (NCCI.PDC.Web.Controls.ucToolTip)row.FindControl("ttcNonStdPolTypeCdEdit");
ttcNonStdPolTypeCdEdit.getEditToolTip("non_std_pol_type_cd", ddl.ID);
}
}
}

A variable declared at class level but initialized in page_load loses its scope in a button_click eventhandler?

im new to asp.net.. please bear with me if ma question is way too trivial!!! :)
im using an accordian control within an update panel. and i also have a button to save some data frm the accordian control! - This complete is a user control which is used in another .aspx page.
now in the page_load event of the user control i initialize my database connection which works absolutely fine while loading data to the accordian.. but when i click on save, in the save button click even handler the database connection object is always null..!! (even though it is initialized in the page_load) please help..
.ascx is as here:
<asp:UpdatePanel ID="PrefPanel" runat="server" >
<ContentTemplate>
<ajaxToolkit:Accordion ID="PrefAccordion" runat="server" HeaderCssClass="accordionHeader"
HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent"
BackColor="#E8EAF7" Height="530px" Width="500px" AutoSize="None" RequireOpenedPane="false"
BorderStyle="Solid" BorderWidth="1" BorderColor="Black">
<Panes>
<ajaxToolkit:AccordionPane ID="ProjCategoryPaneID" runat="server">
<Header > Project Category</Header>
<Content>
<asp:Panel ID="ProjCategoryPanel" runat="server" Width="100%">
<table align="center" width="100%">
<tr></tr>
<tr>
<td align="left">
<asp:CheckBoxList RepeatDirection="Vertical" TextAlign="Left" ID="ProjCategoryItem1" runat="server" AutoPostBack="false" CausesValidation="false" />
</td>
</tr>
</table>
</asp:Panel>
</Content>
</ajaxToolkit:AccordionPane>
<asp:Button ID="btnSavePref" CssClass="buttonsmall" runat="server" Text="Save" Width="60px" OnClick="btnSavePref_Click"/>
<asp:Button ID="btnCancelPref" CssClass="buttonsmall" runat="server" Text="Cancel" Width="60px" />
</ContentTemplate>
</asp:UpdatePanel>
the code behind is as here:
public partial class UserPreferences : System.Web.UI.UserControl
{
private EAReportingDAL m_DataAccessLayer = null;
// Projects Category
Panel projectCategoryPanel;
CheckBoxList projectCategoryList;
protected void Page_Load(object sender, EventArgs e)
{
String connectionString = WebConfigurationManager.ConnectionStrings ["BSCDB"].ConnectionString;
m_DataAccessLayer = new EAReportingDAL(connectionString);
LoadUserPreferences();
}
protected void btnSavePref_Click(object sender, EventArgs e)
{
string userName = this.Page.User.Identity.Name;
DataSet availabeData = m_DataAccessLayer.GetUserPreferences(this.Page.User.Identity.Name, Constants.ProjectsUIView);
}
}
in the button click event handler btnSavePref_Click() the the db connection object m_DataAccessLayer is always null, but whereas the same object in LoadUserPreferences() [which i haven't pasted here though] works fine! plz guide me where im wrong or if someone needs more details!!
I'm not very familiar with UpdatePanel mechanics but maybe you defined it in such a way that it bypass the Page_Load method.
What I suggest is moving the code create the data access layer to separate method then calling this method from both the page load and button click handler:
private void InitDataAccess()
{
//ignore if already created
if (m_DataAccessLayer != null)
return;
String connectionString = WebConfigurationManager.ConnectionStrings ["BSCDB"].ConnectionString;
m_DataAccessLayer = new EAReportingDAL(connectionString);
LoadUserPreferences();
}
protected void Page_Load(object sender, EventArgs e)
{
InitDataAccess();
}
protected void btnSavePref_Click(object sender, EventArgs e)
{
InitDataAccess();
string userName = this.Page.User.Identity.Name;
DataSet availabeData = m_DataAccessLayer.GetUserPreferences(this.Page.User.Identity.Name, Constants.ProjectsUIView);
}

How do I get a reference to a telerik:GridTemplateColumn from a child control?

Simplified code from page:
<%# Page Language="C#" etc... %>
<%# Register src="~/controls/RequiredField.ascx" tagname="rf" tagprefix="custom" %>
<telerik:RadGrid runat="server">
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn DataField="Name" HeaderText="Name" SortExpression="Name">
<ItemTemplate><%#Eval("Name")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="NewName" runat="server" Text='<%#Bind("Name")%>'></asp:TextBox>
<custom:rf runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
In my control, I want to check if the parent is an EditItemTemplate and then set a property of the telerik:GridTemplateColumn. For example:
public partial class controls_RequiredField : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.Parent is Telerik.Web.UI.GridEditFormItem.EditFormTableCell)
{
// how do I get a reference to 'Telerik.Web.UI.GridTemplateColumn' (or any other object that lets me set the header text)
((Telerik.Web.UI.GridTemplateColumn)this.Parent.Parent).EditFormHeaderTextFormat = "{0}:" + RequiredText.Text;
RequiredText.Visible = false;
}
}
}
I don't have the telerik:RadGrid but it is pretty similar to the MS GridView, so I was able to test your issue using asp:GridView (both inherit from CompositeDataBoundControl Class (System.Web.UI.WebControls))
since your custom control is located in the EditItemTemplate your RequiredField control's Page_Load event will not fire until the RadGrid switches to edit mode so you should be able to drop the if (this.Parent is...) check as you'll know the grid is in edit mode.
So with the custom control's page load indicating the grid is in edit mode you can set the HeaderText of the GridTemplateColumn by doing something like:
if (typeof(DataControlFieldCell) == Parent.GetType())
{
((DataControlFieldCell)this.Parent).ContainingField.HeaderText = "Your Custom Heading"; // Or += if appending
}
Well this is the code I'm currently using that works:
protected void Page_Init(object sender, EventArgs e)
{
if (this.Parent is GridEditFormItem.EditFormTableCell)
{
GridEditFormItem.EditFormTableCell parentCell = (GridEditFormItem.EditFormTableCell)this.Parent;
string col = parentCell.ColumnName;
// ridiculous:
Control parentFormItem = this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent;
if (parentFormItem is GridItem)
{
GridItem gi = (GridItem)parentFormItem;
GridColumn parentColumn = gi.OwnerTableView.Columns.FindByUniqueNameSafe(col);
if (parentColumn != null)
{
parentColumn.EditFormHeaderTextFormat = "{0}:" + RequiredText.Text;
RequiredText.Visible = false;
}
}
}
}
But having to cycle up through all those .Parents makes me uneasy.

Resources