.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

GridView and FindControl issue..

Posted By:      Posted Date: October 14, 2010    Points: 0   Category :ASP.Net

Hi guys,

I dont seem to find any control using the FindControl method over gridviews "on edit". I have pasted my code below, please tell me if m doing something wrong or missing something..

ASPX page:

<asp:GridView ID="gvCountry" runat="server" AutoGenerateColumns="False" 
                <asp:TemplateField HeaderText="Edit">
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" 
                            CommandName="Update" Text="Update"></asp:LinkButton>
                         <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" 
                            CommandName="Cancel" Text="Cancel"></asp:LinkButton>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" 

View Complete Post

More Related Resource Links

GridView EmptyDataTemplate and FindControl Method


I have 2 textboxes, a dropdownlist and a button in the EmptyDataTemplate of a GridView control and when I click the button I want to get the text from the text boxes and DropDownList put it in the QueryString of a URL i redirect to, but I can't work out why the FindControl method cannot find the controls.  I am using the following code:

Dim ddlNumPpl As DropDownList = GridView1.FindControl("ddlNumPpl")

I get an "Object reference not set to an instance of an object" error though when I try to refer to the SelectedValue property of it though.  I would be very grateful if someone could let me know why the FindControl method can't find the control and what I should do to rectify it.

Many Thanks (in advance),


Grouping Issue in Gridview

Consider Table in Database Table Name: Work_Order   Work_Id Height Width Thickness Material Shape 11-1 20.3 32.5 50.2 Steel U 11-2 20.3 32.5 50.2 Steel O 11-3 20.3 32.5 50.2 Steel U 11-4 22.3 32.5 50.2 Iron V 11-5 22.3 32.5 50.2 Iron V 11-6 30.3 52.5 63.2 Steel O 11-7 30.3 52.5 63.2 Steel U   Please Provide me the Sqlcommands and method to display the above in an asp.net  Grid View as shown below.   Material Height Width Thickness Shape Steel         11-1 20.3 32.5 50.2 U 11-2 20.3 32.5 50.2 O 11-3 20.3 32.5 50.2 U Steel         11-6 30.3 52.5 63.2 U 11-7 30.3 52.5 63.2 U Iron         11-4 22.3 32.5 50.2 V 11-5 22.3 32.5 50.2 V  Basically I would like group above by Material and check if Height,Weight, Thickness (shape not beconsidered) are same.Is it possible to display the above?

Gridview Grouping issue

Consider a table in DatabaseTable name: Work_OrderWork_Id     Height        Width        Thickness    Material     Shape11-1             20.3cm       32.5cm       50.2cm        Steel            U 11-2             20.3cm       32.5cm       50.2cm        Steel            V11-3             42.3cm       72.5cm       80.5cm        Steel            O11-4             42.3cm       72.5cm       80.5cm        Steel            U11-5             30.3cm       62.5cm       25.2cm        Iron              V11-6             30.3cm       62.5cm       25.2cm        Iron              U Please Provide me the Sql commands a

Gridview Performance Issue

Hi All, I have one ASP.NET Application (VS.NET 2005). In that i have one scenario where i have to display 500 records per page (Not less than that bcoz this is client requirement to display 500 records per page) in the Gridview. This functionality is working fine but the application is becoming very slow. Can anybody tell me the solution for increasing performance in this case ???? VERY URGENT...PLZ REPLY SOON Thanks, Biswajit

Gridview placing issue

hi all,       Actually I am binding 5 gridviews on a form. I done that if gridvew having nay data then it should visible others wise invisible.       there  all 5 gridvew may have data or not and may be 2 or 3 of them having data, depens on the condition.        If gridview1, gridview2, gridview3 dont bind any data then they dont appear on the form only gridview4, gridview5 are binding data and they are appearing on the form. but ther are very down in the form, what I want is ; which ever gridview bind the data it showld not show space bitween form head and the gridview, means if upper all 4 grid are not binding and 5th is binding the it should not appear in the bottom of the form instead it should visible on the top. it's like there are no grid except this grod on the form, i dont need to scroll the form to view the grid.thanksGaurav

findcontrol problem in a gridview

Hey guys I've got a gridview with a few textboxes in each row which I want to insert into a database, after a user clicks a submit button (thats outside of the gridview)  This is my code for the gridview<asp:GridView ID="GridView2" AutoGenerateColumns="false" runat="server" EnableModelValidation="True"> <Columns> <asp:TemplateField > <ItemTemplate> name: <asp:Label ID="Label12" runat="server" Text='<%# Bind("PlayN") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:TextBox ID="TxtFirst" runat="server"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:TextBox ID="txtLast" runat="server"></asp:TextBox> </ItemTemplate>

dropdownlist controls in gridview issue

 the below code creates drop down each time i add a category to the database table. however, i don't wish to have drop down created each time - how can i have all my data in one drop down? thanks...  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CascadingDropDownTestConnectionString %>"  SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Category]">  </asp:SqlDataSource>    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"  DataSourceID="SqlDataSource1">  <Columns>  <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False"  ReadOnly="True" SortExpression="CategoryID" />  <asp:TemplateField HeaderText="Categories">  <ItemTemplate>  <asp:DropDownList ID="ddlCategories" AutoPostBack="true" DataTextField="CategoryName"  DataValueField="CategoryID" DataSourceID="SqlDataSource1" runat="server" AppendDataBoundItems="true"  SelectedValue='<%# Bind("CategoryID") %>' />  &

Gridview Fixed Header Issue


   position:relative ;
   z-index: 10;
2.Assign Datagrid Header's cssClass to Freezing
<HeaderStyle ... CssClass= "Freezing" ...></HeaderStyle>


This is working fine in Internet Explorer but not working in firefox. can anybody please help me to say why its not working in firefox

Why it returns null (GridView)TemplateContainer.FindControl("gridView")?



I created a new custom field definition.

But on CreateChildControls event it always return null in my components. Where is error? What should I do to make work it properly?


protected override void CreateChildControls()


if (this.Field == null) return;


if (this.Field != null && this.ControlMode!= SPControlMode.Display)

this.MyPrefix = (Label)TemplateContainer.FindControl("MyPrefix");
if (this.MyPrefix == null)
    throw new ArgumentException("Corrupted PermissionControl template - missing ProofHQUserPermissionPrefix.");
this.gridView = (GridView)TemplateContainer.FindControl("gridView");
if (this.gridView == null)
    throw new ArgumentException("Corrupted PermissionControl template - missing GridView.");



All components are defined in template PermissionControl.

FormView EditMode Findcontrol issue


Hi All,

I have a simple FormView (fvDespatchPart) which updates the status of an order and it's despatch date; the despatch date being retrieved from a textbox (txtRentalDespatchDate) held within the FormView. The FormView's DefaultMode is set to Edit.

I have been trying to set the default entry for txtRentalDespatchDate to today's date in the code behind, using:

Dim dtNow As Date = Today()

Dim txtRentalDespatchDate As Webcontrols.Textbox = fvDespatchPart.FindControl("txtRentalDespatchDate")

txtRentalDespatchDate.Text = dtNow.ToShortDateString()

but this always returns a

"Object reference not set to an instance of an object." error


I have had no trouble doing this in the past with FormViews whose default mode is set to Insert or Item, but in Edit mode it just does not seem to want to co-operate. I have read a few help posts, and have tried:

Putting that code in LoadComplete, PreRender, PreRenderComplete Page events, as well as the FormView's databound event. I've also tried nesting it within a ...

If fvDespatchPart.CurrentMode = FormViewMode.Edit Th

One Gridview & Multiple CommandText Issue on Paging


Hi All,

I am using a gridview to display data from two separate functions. [VS 2010 on Framework 4]

This works fine without paging. On paging, clicking 'next page' invokes the older data(of function 1) instead of that in the new function (function 2) Cry


' Function 1

cmd.CommandText = "select * from table1,
Dim dTable As DataTable
Dim dataAdapter As SqlDataAdapter
            dTable = New DataTable
            dataAdapter = New SqlDataAdapter(cmd.CommandText, AquisitionString)

'Function 2

cmd.CommandText = "select * from table2,
Dim dTable As DataTable
Dim dataAdapter As SqlDataAdapter
            dTable = New DataTable
            dataAdapter = New SqlDataAdapter(cmd.CommandText, AquisitionString)

'Handling PageIndexChange

   Protected Sub grdAcquisition_PageIndexChanging(ByVal sender As Object, _
       ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdAcquisition.PageIndexChanging

display message if gridview has no row issue


(1) i want to show message if no data row is found in the grid. but my code below does not achieve this. basically if gridview shows data then i want my panel (booking form) to be made visible otherwise hidden. the booking form panel is set to visible false. my else statement is not working...

        protected void btnCheckFlightAvailability_Click(object sender, EventArgs e)
            if (Page.IsPostBack)
                this.gvSingleFlightSearch.DataSourceID = "CheckSingleFlightDataSource";

                if (gvSingleFlightSearch.EmptyDataText != null)
                    pnlFlightAvailableMessage.Visible = true;
                    lblAvailableFlights.Text = "Flight Available";
                    gvSingleFlightSearch.Visible = true;


                        pnlFlightAvailableMessage.Visible = false;
                        lblAvailableFlights.Text = "No Flight Available";
                        gvSingleFlightSearch.Visible = false;

(2) one of the field in my grid view is price while a texbox in my booking form is passenger numbers. how can i use the value entered

Performance issue with GridView


Hi All,

             i am facing performance issue while using the datagrid in my project, i am writing my code here please correct me if i am writing something wrong.

i am using sql server 2000 in which i have a table containing around 600000 records and i can not put any indexing on this table as this is the staging table for me .

now To show these record on front end i am using gridview with Allowpaging = "True" now in the PageIndexChanged event i have to again hit the database and bind the grid which results very slows performance as just to change the page i have to read 600000 records again and again, i am giving some idea below what i am doing

Public Void BindgridView()


//do database connection

//fill the dataset through adapter

Gridview.datasource = dataset();



protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
      GridView1.PageIndex = e.NewPageIndex;

Any idea how can i imrove the performance, Please help me out..



GridView row onclick issue



I'm trying to add multiple statements to a onclick attribute of a Gridview row:

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
string script = (Session[SessionKeys.MarkblokSagNoegle] != null)
? "return confirm('Der er allerede en sag under behandling hvis du genoptager en anden vil denne sag forsvinde!'); "
: "";

script += Page.ClientScript.GetPostBackEventReference((Control) sender,
e.Row.RowIndex)) + ";";
e.Row.Attributes.Add("onclick", script);

Something must be wrong with the way I concat the string 'script' with the statement that makes the row selectable. when the session var is null, then the Page.ClientScript statement goes through and the row will be selectable, but when the session var is NOT null and as a result, the whole statement contains the 'confirm' part, the the confirmation dialog pops up but nothing else happenes upon confirming.

What's wrong with the "script += Page.ClientScript.GetPostBackEv..." part?


Sorting Issue in Gridview with Datasource



am having trouble figuring this one out.

Am using stored procedure and using databind for the gridview . i got the codes off other sites. I'm guessing its the code that i've underlined,
how or what do i use as the datasource for the sorting event. I used the Session for the paging event and that works but not for sorting.
any help would be appreciated.

 protected void LoadComplaint()

            gvComReport.DataSource = CompTypeStatusBLL.GetComplaint(ddlStatus.SelectedValue, ddlType.SelectedValue);
            Session["MyDataSet"] = gvComReport.DataSource;


 protected void gvComReport_Sorting(object sender, GridViewSortEventArgs e)
            DataTable dtSortTable = Session["MyDataset"] as DataTable;

            if (dtSortTable != null)
                DataView dvSortedView = new DataView(dtSortTable);
                dvSortedView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

                gvComReport.DataSource = dvSortedView;

 private string ConvertSortDirectionToSql(SortDirection sortDirection)
            string newSortDirection = St

Collapsible gridview Issue



I have a gridview where I have added Collapsible panel extender. When I am running Its working fine for 1st Row. but when I click in 2nd row, Nothing happens. Below is code.


      <asp:GridView ID="gvGridRisk" runat="server" CssClass="tableGrid"  AutoGenerateColumns="False" AllowSorting="True" 
             DataKeyNames="GridRisklName" onrowdatabound="gvGridRisk_RowDataBound"     ShowHeader="False" GridLines="None">
                 <asp:TemplateField HeaderText="Access Level" ShowHeader="False" >                         
                  <asp:Label ID="lblAccessLevel" runat="server" Text='<%# Bind("GridRisklName")%>'></asp:Label>                               
                    <asp:Panel ID="pnlAccountGroup"

gridview cell value via FindControl......


I have a page that is using an unbound gridview, that has a mixture of template based columns (drop down list, text boxes, etc).  I've tried the following syntax to retrieve the values currently in the cells.


 TextBox1.Text = grdDataEntry.Rows(1).FindControl("mydropdownlist").ToString        

TextBox2.Text   = grdDataEntry.Rows(1).FindControl("mytextbox").ToString


What am I missing???

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend