Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When i am editing in gridview i am getting error like this Object reference not set to an instance of an object.

Here is my code.
C#
public List<products> GetProducts()
        {
            string query = "Select ProductID, ProductName, UnitPrice, UnitsinStock, CategoryID, Discontinued from Products";
            con = new SqlConnection(cons);
            cmd = new SqlCommand(query, con);
            try
            {
                con.Open();
                dr = cmd.ExecuteReader();
                List<products> lst = new List<products>();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        Products pd = new Products();
                        pd.Productid = Convert.ToInt32(dr[0]);
                        pd.ProductName = dr[1].ToString();
                        pd.UnitPrice = Convert.ToInt32(dr[2]);
                        pd.UnitsinStock = Convert.ToInt32(dr[3]);
                        pd.CategoryID = Convert.ToInt32(dr[4]);
                        pd.Discontinued = Convert.ToBoolean(dr[5]);
                        lst.Add(pd);
                    }
                }
                return lst;

            }
            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                con.Close();
            }
        }

Edit Product -
C#
protected void EditProduct(object sender, GridViewEditEventArgs e)
       {
           gv.EditIndex = e.NewEditIndex;
           GetProducts();
       }


gv_rowdatabound event.
C#
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
       {
           if (e.Row.RowType == DataControlRowType.DataRow && gv.EditIndex == e.Row.RowIndex)
           {
               DropDownList ddlist = (DropDownList)e.Row.FindControl("ddlcategoryid");
               ddlist.DataSource = cbl.GetCategories();
               ddlist.DataTextField = "CategoryID";
               ddlist.DataValueField = "CategoryName";
               ddlist.DataBind();
               ddlist.Items.FindByValue((e.Row.FindControl("lblcategoryid") as Label).Text).Selected = true;

           }
       }
   }

After passing rowdatabound event it is getting this error: Object reference not set to an instance of an object.

Please help me thank you.

[edit] Added error information from comment below (bold) - Nelek [/edit]
Posted
Updated 15-Apr-12 0:40am
v3
Comments
Mohamed Mitwalli 15-Apr-12 1:32am    
What is the error message
sreekanth12 15-Apr-12 2:57am    
Object reference not set to an instance of an object.

verify these things in your code :-
- lblcategoryid text should be present as a value in ddlist while you are calling completed of GetCategories
- second one check text case(lower or upper) of label. it should be same as dropDown Value.
you can check before using "FindByValue()"
C#
string str1 =  ddlist.SelectedValue;  //"product1"
string str2 = e.Row.FindControl("lblcategoryid") as Label).Text // "Product1"
 
Share this answer
 
v2
I soleved my problem. i added objectdatasource and i kept dropdownlist selectedvalue
here is my solution.
XML
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false"
           DataKeyNames="CustomerID" OnRowEditing="EditCustomer"
           onrowcancelingedit="gv_RowCancelingEdit"
           onrowupdating="gv_RowUpdating">
           <Columns>
              <asp:CommandField ShowEditButton="true" ShowDeleteButton="true" />
               <asp:TemplateField HeaderText="CustomerID" SortExpression="CustomerID">
                   <ItemTemplate>
                       <asp:Label ID="lblCustomerid" runat="server" Text='<%# Eval("CustomerID") %>'></asp:Label>
                   </ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="CustomerName" SortExpression="CustomerName">
                   <ItemTemplate>
                       <asp:Label ID="lblCustomerName" runat="server" Text='<%# Eval("CustomerName") %>'></asp:Label>
                   </ItemTemplate>
                   <EditItemTemplate>
                       <asp:TextBox ID="txtcustomername" runat="server" Text='<%# Bind("CustomerName") %>'></asp:TextBox>
                   </EditItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="City" SortExpression="City">
                   <ItemTemplate>
                       <asp:Label ID="lblcity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
                   </ItemTemplate>
                   <EditItemTemplate>
                       <asp:DropDownList ID="ddlcity" runat="server" AutoPostBack="True"
                           DataSourceID="ObjectDataSource1" DataTextField="City"
                           DataValueField="City" SelectedValue='<%# Bind("City") %>' ></asp:DropDownList>
                   </EditItemTemplate>
               </asp:TemplateField>
           </Columns>
       </asp:GridView>
       <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
           SelectMethod="GetAddress" TypeName="BusinessLogicLayer.Customersbll">
       </asp:ObjectDataSource>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900