Solved

Add button problem in Gridview

Posted on 2013-11-29
7
607 Views
Last Modified: 2013-12-02
Hi,
when running the project, using Access DB, I get this

Server Error in '/App17_devst' 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:


 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:



[NullReferenceException: Object reference not set to an instance of an object.]
   Add_ite._Default.AddNewRec(Object sender, EventArgs e) +784
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3803

 


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408  

once I've clicked the Add button of the Gridview. Here is the event of the Add button

        protected void AddNewRec(object sender, EventArgs e)
        {
            int ite_id = Convert.ToInt16(lb_iteid.Text);
            DropDownList ddl=(DropDownList)GridView1.FooterRow.FindControl("ddl3");
            int int_id=11;
            if (ddl.Items.FindByValue((GridView1.FooterRow.FindControl("tb_int_id") as TextBox).Text) != null)
            {
                int_id = Convert.ToInt16((GridView1.FooterRow.FindControl("tb_int_id") as TextBox).Text);
            }
            string int_desc = ((TextBox)GridView1.FooterRow.FindControl("tb_int_desc")).Text;
            DateTime change_date = Convert.ToDateTime(((Label)GridView1.FooterRow.FindControl("lblchangedate")).Text);
            //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn2"].ConnectionString);
            //SqlCommand cmd = new SqlCommand();
            OleDbConnection conn = null;
            conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=?????;Data Source=C:\inetpub\VS2012\DB1.accdb");
            OleDbCommand cmd = null, cmd2 = null;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into [ite_tab] ([ite_id], [int_id], [int_desc], [change_date]) " +
            "values(@ite_id, @int_id, @int_desc, @change_date)";
            cmd.Parameters.Add("@ite_id", OleDbType.Integer).Value = ite_id;
            cmd.Parameters.Add("@int_id", OleDbType.Integer).Value = int_id;
            cmd.Parameters.Add("@int_desc", OleDbType.VarChar).Value = int_desc;
            cmd.Parameters.Add("@change_date", OleDbType.DBDate).Value = change_date;
            cmd.ExecuteNonQuery();

            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "select [ite_id],[int_id],[int_desc],[change_date] from [ite_tab] where [ite_id]=@ite_id2";
            cmd2.Parameters.Add("@ite_id2", OleDbType.Integer).Value = ite_id;
            GridView1.DataSource = GetData(cmd2);
            GridView1.DataBind();
        }

Open in new window

and here is the Gridview

    <asp:GridView ID="GridView1" runat="server"  Width = "550px"
    AutoGenerateColumns = "false" Font-Names = "Arial"
    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
    HeaderStyle-BackColor = "green" AllowPaging ="true"  
    ShowFooter = "true" OnPageIndexChanging="GridView1_PageIndexChanging" 
    OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" 
    OnRowUpdating="GridView1_RowUpdating" PageSize = "10" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
    <asp:TemplateField HeaderText="Item">
        <ItemTemplate>
            <asp:DropDownList ID="ddl" OnSelectedIndexChanged="ddl_IndexChanged" AutoPostBack="true" runat="server">
            </asp:DropDownList>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:DropDownList ID="ddl2" OnSelectedIndexChanged="ddl_IndexChanged" AutoPostBack="true" runat="server">
            </asp:DropDownList>
        </EditItemTemplate>
        <FooterTemplate>
            <asp:DropDownList ID="ddl3" OnSelectedIndexChanged="ddl_IndexChanged" AutoPostBack="true" runat="server">
            </asp:DropDownList>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField Visible="false">
        <ItemTemplate>
            <asp:TextBox id="tb_int_id" runat="server" Text='<%# Eval("int_id") %>' Visible="false" />
            <asp:TextBox id="tb_int_desc" runat="server" Text='<%# Eval("int_desc") %>' Visible="false" />
            <asp:TextBox id="tb_int_id2" runat="server" Text='<%# Eval("int_id") %>' Visible="false" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox id="tb_int_id" runat="server" Text='<%# Eval("int_id") %>' Visible="false" />
            <asp:TextBox id="tb_int_desc" runat="server" Text='<%# Eval("int_desc") %>' Visible="false" />
            <asp:TextBox id="tb_int_id2" runat="server" Text='<%# Eval("int_id") %>' Visible="false" />
        </EditItemTemplate>
        <FooterTemplate>
            <asp:TextBox id="tb_int_id" runat="server" Text='<%# Eval("int_id") %>' Visible="false" />
            <asp:TextBox id="tb_int_desc" runat="server" Text='<%# Eval("int_desc") %>' Visible="false" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField ItemStyle-Width = "150px"  HeaderText = "Change Date">
        <ItemTemplate>
            <asp:Label ID="lblchangedate" runat="server"
                Text='<%# Eval("change_date")%>'>
            </asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:Label ID="lblchangedate" runat="server" 
                Text='<%# Eval("change_date")%>' >
            </asp:Label>
        </EditItemTemplate>
        <FooterTemplate>
            <asp:Label ID="lblchangedate" runat="server" 
                Text='<%# Eval("change_date")%>' >
            </asp:Label>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Delete?">
        <ItemTemplate>
            <span onclick="return confirm('Are you sure to delete the record?')">
                <asp:LinkButton ID="lnkdelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete"/>
            </span>
        </ItemTemplate>
        <FooterTemplate>
            <asp:Button ID="btnadd" runat="server" Text="Add" OnClick="AddNewRec" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:CommandField ShowEditButton="true" />
    </Columns>
    <AlternatingRowStyle BackColor="White"/>
    <EditRowStyle BackColor="#efefef" />
    <FooterStyle BackColor="#507CD1" Font-Bold="true" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="true" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="true" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>

Open in new window

0
Comment
Question by:HuaMinChen
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 8

Expert Comment

by:Mohit Vijay
ID: 39686853
What is the line of code @ 784 line number?
0
 
LVL 10

Author Comment

by:HuaMinChen
ID: 39686889
Thanks. Here are some codes with line number
770                catch (SqlException ex)
771                {
772                    ...
773                    //return;
774                }
775                catch (Exception ex)
776                {
777                    ...
778                    //return;
779                }
780                finally
781                {
782                    ...
783                    conn.Close();
784                }

Open in new window

0
 
LVL 8

Expert Comment

by:Mohit Vijay
ID: 39686909
Can you try this once

finally
781                {
782                    if(conn != null)
783                    conn.Close();
784                }
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 10

Author Comment

by:HuaMinChen
ID: 39686971
Hi,
I've put what you mentioned. Then redeployed it and reran it. But I still get the same problem below once I've clicked "Add" button within Gridview.

Server Error in '/App17_devst' 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:


 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:



[NullReferenceException: Object reference not set to an instance of an object.]
   Add_user._Default.AddNewRec(Object sender, EventArgs e) +784
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3803

 


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
0
 
LVL 10

Author Comment

by:HuaMinChen
ID: 39688944
Any help?
0
 
LVL 15

Accepted Solution

by:
JimFive earned 140 total points
ID: 39689935
It looks to me like you might need to set the connection of the command objects:
cmd.connection = conn
cmd2.connection = conn
0
 
LVL 8

Expert Comment

by:Mohit Vijay
ID: 39690024
can you send me code written in finally block. It seems after adding code given by me you are still getting error on 784 line number. After applying code given by me should change the line number atleast, if its unresolved.
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

It’s been over a month into 2017, and there is already a sophisticated Gmail phishing email making it rounds. New techniques and tactics, have given hackers a way to authentically impersonate your contacts.How it Works The attack works by targeti…
The Windows Phone Theme Colours is a tight, powerful, and well balanced palette. This tiny Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing WithEvents, one of Access' hidden gems.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Using Microsoft Access, learn some simple rules for how to construct tables in a relational database. Split up all multi-value fields into single values: Split up fields that belong to other things into separate tables: Make sure that all record…

739 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