Solved

Trying to populate a dropdown list nested in a gridview

Posted on 2011-09-29
9
194 Views
Last Modified: 2012-05-12
I have a GridView, and in there I have a combo box:
<asp:GridView ID ="gvResults" runat ="server" 
    AutoGenerateColumns ="False" 
    BackColor ="White" 
    BorderColor ="#CCCCCC" 
    BorderStyle ="None" 
    BorderWidth ="1px" CellPadding ="3"
    OnRowEditing="gvResults_RowEditing"
    OnRowDataBound="gvResults_RowDataBound"
    ShowFooter="True"> 

~~~~code~~~~

<asp:TemplateField HeaderText="IP2" HeaderStyle-HorizontalAlign="Left"> 
            <EditItemTemplate> 
                <asp:DropDownList ID="ddlIP2" runat="server" DataValueField="Server_IP" /> 
            </EditItemTemplate> 
            <ItemTemplate> 
                <asp:Label ID="lblIP2" runat="server" Text='<%# Eval("SErver_IP") %>'></asp:Label> 
            </ItemTemplate> 
            <FooterTemplate> 
                <asp:DropDownList ID="ddlIP2" runat="server" DataValueField="Server_IP" />
            </FooterTemplate> 
        </asp:TemplateField> 

~~~~more code~~~~

Open in new window



Now for the Codebehind:
    protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DropDownList cmbNewType = (DropDownList)e.Row.FindControl("ddlIP2");
        string sqlQuery = "SELECT Server_IP from fulllist";
        SqlConnection conn = new SqlConnection("Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True");
        SqlDataAdapter sda = new SqlDataAdapter(sqlQuery, conn);
        DataTable dtData = new DataTable();

        DropDownList cmbType = (DropDownList)e.Row.FindControl("ddlIP2");
        cmbType.DataSource = dtData.DefaultView;
        cmbType.DataTextField = "Server_IP";
        cmbType.DataValueField = "Server_IP";
        cmbType.DataBind();
        gvResults.DataKeys[e.Row.RowIndex].Values[1].ToString();
    }

Open in new window


I get the following error when trying to render the page:
Server Error in '/' Application.
--------------------------------------------------------------------------------

Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 52: 
Line 53:         DropDownList cmbType = (DropDownList)e.Row.FindControl("ddlIP2");
Line 54:         cmbType.DataSource = dtData.DefaultView;
Line 55:         cmbType.DataTextField = "Server_IP";
Line 56:         cmbType.DataValueField = "Server_IP";
 

Source File: c:\webroot\myDV.aspx.cs    Line: 54 

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   myDV.gvResults_RowDataBound(Object sender, GridViewRowEventArgs e) in c:\webroot\myDV.aspx.cs:54
   System.Web.UI.WebControls.GridView.CreateRow(Int32 rowIndex, Int32 dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, Boolean dataBind, Object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource) +281
   System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) +2167
   System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +71
   System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data) +17
   System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +146
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +260
   myDV.FillGrid() in c:\webroot\myDV.aspx.cs:42
   myDV.gvResults_RowEditing(Object sender, GridViewEditEventArgs e) in c:\webroot\myDV.aspx.cs:64
   System.Web.UI.WebControls.GridView.HandleEdit(Int32 rowIndex) +51
   System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +693
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +69
   System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +109
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +69
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +28
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2980

Open in new window


I know I'm missing some fundamental concept, its been years since I last used ASP.NET
 
0
Comment
Question by:Mike-Po
  • 3
  • 3
  • 3
9 Comments
 
LVL 12

Expert Comment

by:Ramkisan Jagtap
ID: 36816886
i think ur cmbtype object is null. It is unable to find ur dropdown list. Try to debug the code and find why it is coming null.
0
 
LVL 12

Expert Comment

by:jagssidurala
ID: 36816903
Change your code like below

protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if(e.Row.RowType == DataControlRowType.DataRow)
    {

        DropDownList cmbNewType = (DropDownList)e.Row.FindControl("ddlIP2");
        string sqlQuery = "SELECT Server_IP from fulllist";
        SqlConnection conn = new SqlConnection("Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True");
        SqlDataAdapter sda = new SqlDataAdapter(sqlQuery, conn);
        DataTable dtData = new DataTable();

        DropDownList cmbType = (DropDownList)e.Row.FindControl("ddlIP2");
        cmbType.DataSource = dtData.DefaultView;
        cmbType.DataTextField = "Server_IP";
        cmbType.DataValueField = "Server_IP";
        cmbType.DataBind();
        gvResults.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
    }


Refer these links

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx

http://forums.asp.net/t/1346686.aspx/1
0
 

Author Comment

by:Mike-Po
ID: 36816935
I did noice that I forgot to actually fill the dtData with sda.Fill(dtData).

I have implimpented the if statement (didnt even think about headers and footers). Still no joy, I am currently configuring the webserver to allow for debugging with VS. I will persue that avenue.

Thanks for the input so far!
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 12

Expert Comment

by:Ramkisan Jagtap
ID: 36817093
before binding chk cmbType & dtData for null.
0
 

Author Comment

by:Mike-Po
ID: 36817250
THe dtData is getting filled, however cmbType is staying null. So somewhere I'm not refrencing the dropdown list ddlIP2 correctly.
0
 
LVL 12

Accepted Solution

by:
jagssidurala earned 500 total points
ID: 36817305
try with below condition

 if (e.Row.RowType == DataControlRowType.DataRow && 
        (e.Row.RowState == DataControlRowState.Edit)
    {
        // Find control
       
    }
}
0
 
LVL 12

Expert Comment

by:jagssidurala
ID: 36817336
Refer this link

http://www.codeproject.com/KB/webforms/editable_gridview_control.aspx

try this condition

if (e.Row.RowType == DataControlRowType.DataRow)
   {
   if ((e.Row.RowState & DataControlRowState.Edit) > 0)
   {

//find your control
}
}
0
 
LVL 12

Expert Comment

by:Ramkisan Jagtap
ID: 36817380
u have used edittemplate so chk the rowstate and then use find control.
0
 

Author Closing Comment

by:Mike-Po
ID: 36817704
Having added the validation that the row is being edited: && e.Row.RowState == DataControlRowState.Edit which is the state the dropdown list displays in. Resolved my problem.

I knew it was some fundamental logic flaw on my part. Thank you!
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now