Solved

Trying to populate a dropdown list nested in a gridview

Posted on 2011-09-29
9
193 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
 
LVL 12

Expert Comment

by:Ramkisan Jagtap
ID: 36817093
before binding chk cmbType & dtData for null.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

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…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

932 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

11 Experts available now in Live!

Get 1:1 Help Now